5

I have created a xyplot with lattice

library(lattice)
X1=c(5, -2, 1, -3)
X2=X1^2
names=paste("dot", 1:4, sep="")
xyplot(X2~X1, data=data.frame(X1, X2), pch=20, cex=1:4)

Now I want to add a label (text) for each dot. The info is in

names=paste("dot", 1:4, sep="")

I have tried with no success the following

panel.text(x=X2, y=X1, names)

or, using directlabels

library(directlabels)
p=xyplot(X2~X1,data=data.frame(X1, X2), pch=20, group=names, cex=1:4)
direct.label(p,smart.grid,FALSE)

but I don't like it much because I had to split into groups using group=names, basically each dot is in a different group? Is there another way to do it?

Stedy
  • 7,359
  • 14
  • 57
  • 77
RockScience
  • 17,932
  • 26
  • 89
  • 125

1 Answers1

9

You can try defining a new panel function:

xyplot(X2~X1, data=data.frame(X1, X2), pch=20, cex=1:4,
      panel=function(x, y, ...) {
               panel.xyplot(x, y, ...);
               ltext(x=x, y=y, labels=names, pos=1, offset=1, cex=0.8)
            })
Apprentice Queue
  • 2,036
  • 13
  • 13
  • 1
    I should really read a good tutorial on these panels. I don't get why we have to call 2 functions, xyplot AND panel.xyplot – RockScience Jul 07 '11 at 07:37
  • What if I want to provide a vector for pos ? (each dot would have a different number between 1 and 3 for the position) – RockScience Jul 07 '11 at 08:05
  • 2
    @RockScience: `xyplot` draws the whole plot; the function in the `panel` argument tells `xyplot` what to draw in each panel. In this case, it does what `xyplot` usually does (by calling `panel.xyplot`, then draws some extra text (by calling `ltext`, though `panel.text` would make the code clearer). – Richie Cotton Jul 07 '11 at 13:28