0

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, ...)
     }
 )
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
datutu
  • 1
  • 1
  • Now that I understand what you are trying to accomplish, I think that you are taking the wrong approach. The idea with lattice graphics is to show the same parameters (for example, male and female) over different groups (for example, control vs treatment). Here you are just trying to make multiple plots with different data. Instead look at using the `layout` function, or `par:mfrow` to combine multiple plots. – dayne Aug 28 '13 at 14:36

1 Answers1

1

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
}
Bryan
  • 933
  • 1
  • 7
  • 21