The pie()
function takes a Frequency table as input. You can either create the table first and then pass it to the pie()
function or you can create the table directly in the pie()
function.
The data for the examples below comes from the mtcars dataset. The two categorical variables, cylinders and gears are used to show how to create side-by-side pie charts.
mtcars$cyl <- factor(mtcars$cyl)
par(mfrow=c(1,3) ) # 1 row and 3 columns for plots
pie( table(mtcars$cyl[mtcars$gear==3]), col=grey.colors(3), xlab="3 Gears")
pie( table(mtcars$cyl[mtcars$gear==4]), col=grey.colors(3), xlab="4 Gears")
mtext(side=3, text="Number of Cylendars by Gears")
pie( table(mtcars$cyl[mtcars$gear==5]), col=grey.colors(3), xlab="5 Gears")
par(mfrow=c(1,1) )
par(mfrow=c(1,4) ) # 1 row and 3 columns for plots
pie( table(mtcars$cyl[mtcars$gear==3]), col=grey.colors(3), xlab="3 Gears", labels="")
pie( table(mtcars$cyl[mtcars$gear==4]), col=grey.colors(3), xlab="4 Gears", labels="")
mtext(side=3, text="Number of Cylendars by Gears")
pie( table(mtcars$cyl[mtcars$gear==5]), col=grey.colors(3), xlab="5 Gears", labels="")
plot.new()
legend("left",legend=c("4","6","8"), fill=grey.colors(3), box.lty=0, title="Cylinders")
par(mfrow=c(1,1) )
library(ggplot2)
mtcars$cyl <- factor(mtcars$cyl) # converts to a categorical variable
mtcars$gear <- factor(mtcars$gear) # converts to a categorical variable
p <- ggplot(data=mtcars, aes(x=factor(1), stat="bin", fill=cyl)) + geom_bar(position="fill") # Stacked bar chart
p <- p + ggtitle("Cylinders by Gears") + xlab("") + ylab("Gears") # Adds titles
p <- p + facet_grid(facets=. ~ gear) # Side by side bar chart
p <- p + coord_polar(theta="y") # side by side pie chart
p
Mathematicss, Computer Science, and Statistics Department Gustavus Adolphus College