2012-10-30 73 views
11

我在ggplot2中繪製了一個圖,例如2行,在圖例中我有「鯊魚」和「老虎」。有沒有辦法讓鯊魚/老虎圖像出現在圖例中而不是文字中?在ggplot2圖例中使用圖片代替標籤

+1

我不會說這是不可能的,但你R中得到任何的解決方案很可能是WAAAAY不是簡單地發射了Photoshop的困難。 (不過,看看'grid.raster'可能會讓你開始吧。) – joran

+0

或[gimp](http://www.gimp.org/)是爲那裏的開源愛好者準備的。 – Chase

+0

是的,在光柵程序中手工操作是不行的,這是用於大規模重複圖形生成:) – nicolaskruchten

回答

32

使用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) 

shark tiger scariness figure

+1

+1很酷。 –

+8

先生,你應該享用1000種互聯網啤酒。或者可能只是一個鯊魚。隨你便。 – joran

+0

真棒解決方法和示例!謝謝! – nicolaskruchten