Side-By-Side 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 a bar chart.

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

Side-By-Side Bar Chart Using a Dataset

barplot(table1, ylab="Frequency", xlab="Gears", main="Side-By-Side Bar Chart", col=c("turquoise4", "turquoise2", "turquoise" ), beside=TRUE, width=.3)

legend("right", title="Cylinders", legend= sort(unique(mtcars$cyl)), fill =c("turquoise4", "turquoise2", "turquoise" ), box.lty=0)

Mathematicss, Computer Science, and Statistics Department Gustavus Adolphus College