1

Here is a reproducible example to work with:

library(lattice)

myimage<-matrix(c(1,1,2,3,3,4), nrow=3, ncol=2)
mytable<-data.frame(Xcoord=c(1.5, 1.5, 3,3), Ycoord=c(1,2,1,2), Labels=c("A","B","C","D"))
mycolors<-colorRampPalette(c("red","yellow","green","cyan","blue"))

windows()
levelplot(myimage, aspect="iso", col.regions = mycolors)

which produce the graph below. Now I want to add (as text) the Labels in mytable at the specified coordinates indicated by Xcoord & Ycoord (which correspond to the rows and columns of the images). How can I do this ?

enter image description here

user20650
  • 24,654
  • 5
  • 56
  • 91
bricx
  • 593
  • 4
  • 18
  • A quick (and dirty) go is to use a `panel` function e.g. `panel = function(x, y, ...) {panel.levelplot(x, y, ...) panel.text(x=mytable$Xcoord, y=mytable$Ycoord, mytable$Labels) }` – user20650 Dec 08 '21 at 23:08
  • another options https://stackoverflow.com/questions/28270176/add-labels-to-levelplot ; – user20650 Dec 08 '21 at 23:11
  • @user20650 I tried what you are proposing but it doesn't seems to work, nothing is displayed on the graph... looks like my only option is to convert the matrix image into a dataframe and follow the example of the link... I'll try that... – bricx Dec 10 '21 at 16:55
  • 1
    bricx; using the same data as shown in your question, without any changes, and executing `print(levelplot(myimage, aspect="iso", col.regions = mycolors, panel = function(x, y, ...) { panel.levelplot(x, y, ...) panel.text(x=mytable$Xcoord, y=mytable$Ycoord, mytable$Labels) }))` produces the expected plot for me. – user20650 Dec 10 '21 at 21:06
  • ... did you maybe forget to add `panel.levelplot(x, y, ...) ` to the `panel` function? – user20650 Dec 10 '21 at 21:08
  • 1
    That works too indeed, great, thanks! – bricx Dec 10 '21 at 21:13

1 Answers1

1

Only solution I could find is following user20650's link above and converting the matrix image to a data.frame with x, y coordinates (which I would have preferred to avoid):

dat <- data.frame(expand.grid(x = 1:3, y = 1:2), value = c(myimage))

Obj <-
  levelplot(value ~ x+y, data = dat, aspect="iso", col.regions = mycolors) +
  xyplot(y ~ x, data = dat,
         panel = function(y, x, ...) {
           ltext(x = mytable$Xcoord, y = mytable$Ycoord, labels = mytable$Labels, cex = 1, font = 2)
         })

print({Obj})

enter image description here

bricx
  • 593
  • 4
  • 18