How to Add Color and a Key to Lattice Charts in R - dummies

How to Add Color and a Key to Lattice Charts in R

By Andrie de Vries, Joris Meys

Many lattice graphics types in R — but bar charts in particular — tend to display multiple groups of data at the same time. Usually, you can distinguish different groups by their color or sometimes their shading. If you ever want to add different colors to your plot to distinguish between different data, you need to define groups in your lattice plot and then add a key so the reader knows what they mean.

How to define groups in your lattice plot

Say you want to create a bar chart that differentiates whether a car has an automatic or manual gearbox. The mtcars dataset has a column with this data, called am — this is a numeric vector with the value 0 for automatic and 1 for manual. You can use the ifelse() function to convert from numeric values to a character values “Automatic” and “Manual”:

> mtcars$cars <- rownames(mtcars)
> mtcars$am <- with(mtcars, ifelse(am==0, "Automatic", "Manual"))

Now you plot your data using the same formula as before, but you need to add an argument defining the group, group=am.

> barchart(cars ~ mpg | factor(cyl), data=mtcars,
+   group=am,
+   scales=list(cex=0.5),
+   layout=c(3, 1),
+ )

When you run this code, you’ll get your desired bar chart. However, the first thing you’ll notice is that the colors look a bit washed out and you don’t have a key to distinguish between automatic and manual cars.

How to add a key

It is easy to add a key to a graphic that already contains a group argument. Usually, it’s as simple as adding another argument, auto.key=TRUE, which automatically creates a key that matches the groups:

> barchart(cars ~ mpg | factor(cyl), data=mtcars,
+   main="barchart with groups",
+   group=am,
+   auto.key=TRUE,
+   par.settings = simpleTheme(col=c("grey80", "grey20")),
+   scales=list(cex=0.5),
+   layout=c(3, 1)
+ )

One more thing to notice about this specific example is the arguments for par.settings to control the color of the bars. In this case, the colors are shades of gray.