Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

r - Labelling the plots with images on graph in ggplot2

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...