Lattice plots are a great way of displaying multivariate data in R. Deepayan Sarkar, the author of lattice, has written a fantastic book about Multivariate Data Visualization with R . However, I often have to refer back to the help pages to remind myself how to set and change the legend and how to ensure that the legend will use the same colours as my plot. Thus, I thought I write down an example for future reference.
Eventually I would like to get the following result:
I start with a simple bar chart, using the
Insurance data set of the MASS package.
Please note that if you use R-2.15.2 or higher you may get a warning message with the current version of lattice (0.20-10), but this is a known issue, and I don't think you need to worry about it.
library(MASS) <br />library(lattice)<br />## Plot the claims frequency against age group by engine size and district<br />barchart(Claims/Holders ~ Age | Group, groups=District,<br /> data=Insurance, origin=0, auto.key=TRUE)
To change the legend I specify a list with the various options for
auto.key. Here I want to set the legend items next to each other, add a title for the legend and change its font size: Read more »