# 1) Create the Contingency Table for which you want a Pie Chart
tab1 <- table(mtcars$am)
# 2) Calculate percentages %
tab2 = prop.table(tab1)
percent <- round(tab2*100,1)
# 3a) Create labels for each pie in the chart
pielabels <- paste(percent, "%", sep="")
# 3b) Generate the Pie Chart
pie(tab2,
col = c("lightblue","red"),
labels = pielabels,
main = '% of cars by Transmission (am)',
cex = 1.1)
# 3c) Legend for the pie chart
legend("topright",
c("1","0"),
cex=0.8,
fill=rainbow(length(tab2)))# 1) Generate the Contingency Table with Proportions
tab1 <- table(mtcars$cyl)
tab2 <- prop.table(tab1)
tab3 <- round(tab2*100, 2)
# 2) Generate the Bar Plot
bp <- barplot(tab3,
xlab = "cyl", ylab = "Percent (%)",
main = "% Cars by number of cylinders (cyl=4,6,8)",
col = c("yellow"),
beside = TRUE,
ylim = c(0, 60))
# 3) (Optional) Display the percentages on the Bar Plot
text(bp, 0, tab3, pos=3)# 1)
tab1 <- table(mtcars$am, mtcars$cyl)
tab2 <- prop.table(tab1)
tab3 <- round(tab2*100, 2)
# 2) Grouped bar-plot
bp <- barplot(tab3,
xlab = "cyl", ylab = "Percent (%)",
main = "% Cars by number of cylinders (cyl=4,6,8) and transmission (am=0,1)",
col = c("lightblue","orange"),
beside = TRUE,
ylim = c(0, 50),
legend = rownames(tab3))
# 3) (Optional) Display percentage on the bars
text(bp, 0, tab3, pos = 3)