在ggplot2图例中使用图像而不是标签 [英] Use image instead of labels in ggplot2 legend

查看:97
本文介绍了在ggplot2图例中使用图像而不是标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ggplot2中有一个情节,例如2行,在传说中我有鲨鱼和老虎。有没有一种方法可以让鲨鱼/老虎图像出现在传说中而不是文本中? 使用 ggsave 将图保存为 eps svg ,然后在Illustrator中打开它(或等效的开源代码)并用图像替换图例。如果你真的死于R这一切,你可以在当前的 ggplot2 中使用 annotation_raster 并添加在它旁边的一些文本中使用 geom_text 。这是一个粗略的尝试:

pre $ code $ set $($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 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 =动物))+
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 =(nf(df),
ymin = max(df $ scariness) - (.1 * max(df $ scariness)),
ymax = max(df $ scariness) - (。05 * max df $ scariness)),interpolate = T)


I have a plot in ggplot2 with, say, 2 lines, and in the legend I have "Sharks" and "Tigers". Is there a way I could have shark/tiger images appear in the legend instead of that text?

解决方案

You're much better off using ggsave to save the figure as a eps or svg, then opening it in Illustrator (or open source equivalent) and replacing the legend with the images. If you're really dead set on doing it all in R, you can use annotation_raster in the current ggplot2 and add in some text next to it using geom_text. Here is a rough attempt:

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)

这篇关于在ggplot2图例中使用图像而不是标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆