Let's use data to clarify my question. I use our Gapminder data:
Sys.setenv(lang = "EN")
library(plyr)
library(xtable)
library(lattice)
dat <- read.delim("http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt")
I do the following data aggregation task: using ddply, I first split the data according to year, and then within each year I calculate mean, 5th quantile and 95th quantile (which correspond to 90% confidence interval) of life expectancy.
lifeExpMean = ddply(dat, ~year, summarize, mean = mean(lifeExp), q5 = quantile(lifeExp,
probs = 0.05), q95 = quantile(lifeExp, probs = 0.95))
The data aggregation result looks like the following.
print(xtable(lifeExpMean), type = "html")
year | mean | q5 | q95 | |
---|---|---|---|---|
1 | 1952 | 49.06 | 32.57 | 69.18 |
2 | 1957 | 51.51 | 34.58 | 70.33 |
3 | 1962 | 53.61 | 36.20 | 71.22 |
4 | 1967 | 55.68 | 38.13 | 71.55 |
5 | 1972 | 57.65 | 39.99 | 73.05 |
6 | 1977 | 59.57 | 41.72 | 74.38 |
7 | 1982 | 61.53 | 42.99 | 75.74 |
8 | 1987 | 63.21 | 44.60 | 76.66 |
9 | 1992 | 64.16 | 44.31 | 77.56 |
10 | 1997 | 65.01 | 43.83 | 78.76 |
11 | 2002 | 65.69 | 43.76 | 79.78 |
12 | 2007 | 67.01 | 43.87 | 80.74 |
To explain clearly what I want to do with this data, I provide a plot using base graphics in R:
plot(mean ~ year, lifeExpMean, type = "l", lwd = 3, ylim = c(min(lifeExpMean[,
2:4]) - 2, max(lifeExpMean[, 2:4]) + 10))
lines(q5 ~ year, lifeExpMean, type = "l", lwd = 3, col = 2, lty = 3)
lines(q95 ~ year, lifeExpMean, type = "l", lwd = 3, col = 2, lty = 3)
legend("topleft", c("mean", "5th and 95th percentiles"), lty = c(1, 3), col = c(1,
2), lwd = 3)
The plot above has mean with black solid line and quantiles with red dotted lines. The legend explains the lines. The legend command has 5 components: the location of the legend, the texts in the legend, the style of lines, the colors of lines and the thickness of lines in the legend. I want to control these elements of the legend when I use lattice as well.
To draw the plot above with lattice, I tried the following code, but I have trouble with controlling the elements in the legend. By the command below, I can control the location and the texts of the legend, but I cannot control the style, the colors and the thinkness of lines. lty
and lwd
arguments do not work, and the col
argument changes the color of the texts, not the lines. Could you explain how I can control these elements?
xyplot(mean + q5 + q95 ~ year,lifeExpMean,
# controls the lines in the plot. For help, type ?panel.xyplot on R console.
panel=function(x,y,...) panel.xyplot(x,y,...,type="l",col=c(1,2,2),lty=c(1,3,3),lwd=3),
# controls the legend. For help, type ?simpleKey on R console.
auto.key=list(x=0.05,y=0.95,text=c("mean","5th and 95th percentiles"),
points=FALSE, lines=TRUE,col=c(1,2)))