【问题标题】:Use image instead of labels in ggplot2 legend在 ggplot2 图例中使用图像而不是标签
【发布时间】:2012-10-20 08:21:08
【问题描述】:

我在 ggplot2 中有一个情节,比如 2 行,在图例中我有“鲨鱼”和“老虎”。有没有办法让鲨鱼/老虎图像出现在图例中而不是文本中?

【问题讨论】:

  • 我不会说这是不可能的,但你在 R 中获得的任何解决方案都可能比简单地启动 Photoshop 更难。 (不过,查看grid.raster 可能会让您入门。)
  • gimp 供开源爱好者使用。
  • 是的,在光栅程序中手动操作是不行的,这是为了大规模重复图形生成:)
  • 可能可行的解决方案的模糊轮廓:使用文本标签使图形正常化,将其渲染到网格图形/gtable 级别,找到图例文本的 grobs 并用 grobs 替换那些画你的图像。这只是一个模糊的建议,因为我什至不确定如何执行某些步骤。

标签: r ggplot2 graphing


【解决方案1】:

您最好使用ggsave 将图形保存为epssvg,然后在Illustrator(或开源等效程序)中打开它并用图像替换图例。如果你真的想在 R 中做这一切,你可以在当前的 ggplot2 中使用 annotation_raster 并使用 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)

【讨论】:

  • 很棒的代码,让我们都考虑一下“一般情况”,其中 OP 可能想要自动化几十个“动物 [j] 与动物 [k]”的图表并调用一个数据库要绘制的图像。 GIMP/GraphicConverter/Photoshop 对于一张图来说可能更容易,但在处理 10^n (n>=1) 幅图时,自动化总是胜出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 2022-01-03
  • 2017-04-26
  • 2017-01-22
  • 2016-01-05
相关资源
最近更新 更多