Creating bar charts with more than one factor variable

In this first recipe, we will learn how to make bar charts for data with more than one category. Such bar charts are commonly used to compare values of the same measure across different categories.

Getting ready

We will use the base library barplot() function, but we will also use the RColorBrewer package to choose a good color palette. So, let's first install and load that package:

install.packages("RColorBrewer") #if not already installed
library(RColorBrewer)

How to do it...

Let's reuse the citysales.csv example dataset that we used in the first chapter:

citysales<-read.csv("citysales.csv") barplot(as.matrix(citysales[,2:4]), beside=TRUE, legend.text=citysales$City, args.legend=list(bty="n",horiz=TRUE), ...

Get R: Data Analysis and Visualization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.