Search code examples
rplotlabelpointlattice

r: set labels for every point in xyplot {lattice} not for groups


I am sure there is a simple solution for my question but I couldn't find my answer. I would like to put labels for every point value in scatterplot using lattice, not the basic plot. I found that the library(direct.label) can complete this work, nice example here: http://directlabels.r-forge.r-project.org/examples.html. However, the labels here are displaying the name of the group, not display the value/name for every point! I would like to keep my data separated by groups (virginica, versicolor, setosa) but also add there exact value for every point (p.ex. Petal.Width) in the graph. Please, how to complete this? Thank you a lot !

library(lattice)
trellis.par.set(standard.theme(color=FALSE))
p <- xyplot(jitter(Sepal.Length)~jitter(Petal.Length),iris,groups=Species)
direct.label(p)

what I do expect (the red values generated for every point):

enter image description here


Solution

  • You have to use panel.text inside trellis.focus like this:

    p<-xyplot(jitter(Sepal.Length)~jitter(Petal.Length),iris,groups=Species)
    p
    trellis.focus("panel",1,1)
    panel.text(x=p$panel.args[[1]]$x,y=p$panel.args[[1]]$y,labels = iris$Petal.Width, pos=3, cex=0.7, col="red")
    trellis.unfocus()
    

    enter image description here