7

I would like to add different text to each panel in xyplot in lattice.

res<- xyplot(CumSpec ~ CumTotal | Site, data=data1, index.cond=list(c(1,2,3)),layout = c(3,1,1), aspect = 1,
         axis=axis.overlap, origin=0, xlab="Total number of individuals", ylab="Total number of species",
         between = list(x = 0), 
         scales=list(tick.number = 8, cex = .9, x=list(alternating=1), x=list(rot=90)),
         par.settings = my.settings,
         par.strip.text=list(col="white", font=2),
panel = function(x, y) {
panel.xyplot(x, y)

panel.abline(lm(y ~ x), lwd = 0.5, lty=2)
panel.text(400, 4.6, label="R=0.334", font=1)
}) 
res

I have tried to use panel.text but it adds the label to every panel. Does anyone know how to achieve this, please? your help would be appreciated.

Gimelist
  • 791
  • 1
  • 10
  • 25
user48386
  • 95
  • 1
  • 6
  • 1
    It's best to supply [reproducible data](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) or use a built-in dataset so that we can easily recreate your plot and show you how to obtain your desired result. Otherwise this is just some arbitrary code that we can't really do anything with. – Thomas May 21 '14 at 11:17

1 Answers1

7

The basic strategy you want is to first come up with a character vector, where each element in the vector is the text you want on a particular panel. Then you can use the panel.number() function to chose a different element of the character vector for each panel. Here is a simple example:

library(lattice)
X<-rnorm(100)
Y<-rnorm(100)
Z<-c(rep("A",50),rep("B",50))
df1<-data.frame(X,Y,Z)

MyText<-c("Panel 1 Text", "Panel 2 Text")

xyplot(X~Y|Z, data=df1,
   panel=function(x, y,...){
   panel.xyplot(x,y,...)
   panel.text(0,0,labels=MyText[panel.number()]) }
 )

You could use this strategy for anything you want to change from panel to panel (e.g your x- and y-positions for the labels, colors, pch values, etc).

John Paul
  • 12,196
  • 6
  • 55
  • 75
  • Hi . How would you convey a solution for the case someone wants different coordinates for each panel ? – moth Feb 01 '19 at 03:49
  • 1
    @AlexandreMondaini If you want different x and y coordinate for your text, you would make two vectors, say `MyX` and `MyY`, with the x and y coordinates for each panel. Then have `panel.text(x=MyX[panel.number()], y=MyY[panel.number()], labels=MyText[panel.number()])` – John Paul Feb 01 '19 at 13:01
  • thank you I managed to do it. However now I am facing a problem when trying to put to elements of `Mytext` into a single panel, I only managed to use a single element per panel. Do you know how could I achieve this ? – moth Feb 07 '19 at 18:06
  • @AlexandreMondaini You should probably open a new question about this. – John Paul Feb 07 '19 at 18:13