Stacked bar charts are used to display two categorical variables.
The barplot()
function takes a Contingency table as input. You can either create the table first and then pass it to the barplot()
function or you can create the table directly in the barplot()
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 stacked bar charts.
table1 <- table(mtcars$cyl, mtcars$gear, dnn=c("Cylinders", "Gears")) # Creates a contingency table
addmargins(table1) #Displays the table (Not necessary)
## Gears
## Cylinders 3 4 5 Sum
## 4 1 8 2 11
## 6 2 4 1 7
## 8 12 0 2 14
## Sum 15 12 5 32
barplot(table1, ylab="Frequency", xlab="Gears", main="Stacked Bar Chart", col=c("turquoise4", "turquoise2", "turquoise" ), beside <- FALSE, xlim=c(0,1), width=.3)
legend("right", title="Cylinders", legend= sort(unique(mtcars$cyl)), fill =c("turquoise4", "turquoise2", "turquoise" ), box.lty=0)
library(ggplot2) #load ggplot2 library
mtcars$gear <- factor(mtcars$gear) # Create a categorical variable
mtcars$cyl <- factor(mtcars$cyl) # Create categorical variable
p <- ggplot(data = mtcars, aes(x=gear, fill=cyl) ) + geom_bar() # Creates stacked bar chart
p <- p + xlab("Gears") + ggtitle("Cylinders by Gears") # Adds title and labels
p
Mathematicss, Computer Science, and Statistics Department Gustavus Adolphus College