14

So I have this R script that can produce a scatter plot with labels of each point. Sth like this:

img1<-"http://blog.gettyimages.com/wp-content/uploads/2013/01/Siberian-Tiger-Running-Through-Snow-Tom-Brakefield-Getty-Images-200353826-001-628x419.jpg"
img2<-"http://blog.gettyimages.com/wp-content/uploads/2013/01/Hurricane-Sandy-Andrew-Burton-Getty-Images-154986556.jpg"
imgdata<-data.frame(c(img1,img2,img1,img2,img1,img2,img1,img2,img1,img2))
colnames(imgdata)<-"images"
txtdata<-data.frame(c("A","B","C","D","E","F","G","H","I","J"))

plotdata<-data.frame(seq(1:10),seq(11:20),txtdata,imgdata)
colnames(plotdata)<-c("var1","var2","texts","images")
ggplot(data=plotdata, aes(plotdata[,1],plotdata[,2])) + 
  geom_point(data=plotdata, aes(plotdata[,1],plotdata[,2])) +
  geom_text(aes(label=plotdata$points,size=2, hjust=2))

This gives a scatter plot, where each point is labelled as "A", "B", "C"... etc.

What I want to do is almost the same, except instead of texts, I want to label each point with the image that are in the links of a vector or data frame (in this case in "imgdata"). Note that I selected these images just as examples; I have much more of them, so I can't manually download them.

6

1 Answer 1

17

You can use annotation_custom, but it will be a lot of work because each image has to be rendered as a raster object and its location specified. I saved the images as png files to create this example.

library(ggplot2)
library(png)
library(grid)

img1 <- readPNG("c:/test/img1.png")

g1<- rasterGrob(img1, interpolate=TRUE)


img2 <- readPNG("c:/test/img2.png")
g2<- rasterGrob(img2, interpolate=TRUE)


plotdata<-data.frame(seq(1:2),seq(11:12))
ggplot(data=plotdata) +  scale_y_continuous(limits=c(0,4))+ scale_x_continuous(limits=c(0,4))+
  geom_point(data=plotdata, aes(plotdata[,1],plotdata[,2])) +
  annotation_custom(g1,xmin=1, xmax=1.5,ymin=1, ymax=1.5)+
  annotation_custom(g2,xmin=2, xmax=2.5,ymin=2, ymax=2.5) 

enter image description here

3
  • I'll try to put this into a loop and sort it out somehow. It's OK if it'll be computationally expensive, but it's a good solution as long as I can automate it. Thanks!
    – agondiken
    Dec 23, 2013 at 16:00
  • 1
    You're welcome. Do not hesitate to share you final (automated) solution. Dec 23, 2013 at 16:30
  • It appears now that the function rasterGrob has moved to the grid package, part of base R, if I understand correctly, so library(grid) should be used instead of library(gridExtra).
    – PatrickT
    Apr 29, 2016 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.