在ggplot2图例中使用图像而不是标签

nic*_*ten 14 graphing r ggplot2

我在ggplot2中有一个情节,例如2行,在传说中我有"鲨鱼"和"老虎".有没有办法让鲨鱼/老虎图像出现在图例而不是文字中?

Mai*_*ura 34

你最好使用ggsave将图形保存为eps或者svg,然后在Illustrator中打开它(或等效的开源)并用图像替换图例.如果你真的死在R中做全部,你可以annotation_raster在当前使用并在其ggplot2旁边添加一些文本geom_text.这是一个粗略的尝试:

set.seed(10)
library(ggplot2) 
library(RCurl)
library(png)
df <- data.frame(animal = sample(c("sharks", "tigers"),20, rep=T), time=1:20, 
                 scariness = rnorm(20)*-20)

shark <- readPNG(getURLContent("http://i.imgur.com/EOc2V.png"))
tiger <- readPNG(getURLContent("http://i.imgur.com/zjIh5.png"))

ggplot(df, aes(time, scariness, group = animal, color = animal)) + 
geom_line(show_guide = FALSE) +
 annotation_raster(tiger, xmin = nrow(df)-1, xmax = nrow(df), 
    ymin = max(df$scariness)-(.05*max(df$scariness)), 
    ymax = max(df$scariness), interpolate = T) +
 annotation_raster(shark, xmin = nrow(df)-1, xmax = nrow(df), 
    ymin = max(df$scariness)-(.1*max(df$scariness)), 
    ymax = max(df$scariness)-(.05*max(df$scariness)), interpolate = T)
Run Code Online (Sandbox Code Playgroud)

鲨鱼虎疤痕的身影

  • 伟大的代码,让我们都考虑"一般情况",OP可能想要自动化几十个"动物[j]与动物[k]"的图形,并调用图像数据库进行绘制.对于一个图形,GIMP/GraphicConverter/Photoshop可能更容易,但在执行10 ^ n(n> = 1)图形时,自动化总是会获胜. (2认同)