datutu
datutu

Reputation: 1

Add legend inside each panel with Lattice in R

I wanna make a scatter plot with connecting lines for different groups and different individuals. I make panels conditioned by my group variable and groups conditioned by my individual variables. Now, I would like to add legend inside each panels(see the code below). In the plots, I would like to have legends of individuals for GRP==1 in the first panel, GRP==2 in the second panel, so on so forth. All the legends are located in the upper left corner of the panel they belong to. How shall I code?

library(lattice)
mydata   <- data.frame(ID = rep(1: 20, each = 10),
                       GRP = rep(1: 4, each = 50), 
                       x = rep(0: 9, 20))
mydata$y <- 1.2 * mydata$GRP * mydata$x + 
            rnorm(nrow(mydata), sd = mydata$GRP)

xyplot(y~ x | factor(GRP), data = mydata,
     groups = ID,
     type = "b",
     as.table = T,
     layout = c(2, 2),
     panel = panel.superpose,
     panel.groups = function (x, y, ...) {
         panel.xyplot(x, y, ...)
     }
 )

Upvotes: 0

Views: 1976

Answers (1)

Bryan
Bryan

Reputation: 933

Try something like this. Note that the subset command comes in the data statement in xyplot. This is on purpose. If you call subset as an xyplot argument, then the plots would have shown all 20 labels in each plot.

library(lattice)
mydata <- data.frame(ID = rep(1:20, each = 10), GRP = rep(1:4, each = 50), x = rep(0:9, 20))
mydata$y <- 1.2 * mydata$GRP * mydata$x + rnorm(nrow(mydata), sd = mydata$GRP)

i=1; j=1
for(grp in 1:4) {
      a <- xyplot(y~x|factor(GRP), data=subset(mydata, GRP==grp),
                  groups = factor(ID),
                  type = "b",
                  auto.key=list(columns=4,space="inside")
                  )
  print(a, split=c(i,j,2,2), more=T)
  i=i+1; if(i>2){i=1;j=j+1} # basically, tell the plots which quadrant to go in
}

Upvotes: 1

Related Questions