How to Work with Scales in a ggplot2 in R
How to Hunt for Bugs in R
How to Go Beyond Date and Time Basics in R

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

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Name the Values in Your Vectors in R
How to Plot Histograms with Your Data in R
How to Present Dates in Different Formats in R
How to Convert a Factor in R
How to Debug Your Code in R