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?
Asked
Active
Viewed 3,153 times
18
-
2I'm not going to say that this is impossible, but any solution you get in R is likely to be WAAAAY harder than simply firing up Photoshop. (Looking at `grid.raster` might get you started, though.) – joran Oct 30 '12 at 22:28
-
or [gimp](http://www.gimp.org/) for the open source aficionados out there. – Chase Oct 30 '12 at 22:36
-
Yeah, doing it by hand in a raster program is a no-go, this is for large-scale repeated graph generation :) – nicolaskruchten Oct 31 '12 at 00:40
-
1Vague outline of a solution that might work: make the graph as normal with text labels, render it down to the grid graphics/gtable level, find the grobs for the legend text and replace those with grobs that draw your images instead. This is just a vague suggestion because I'm not even sure how to do some of the steps. – Brian Diggs Oct 31 '12 at 03:57
1 Answers
38
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)

Maiasaura
- 32,226
- 27
- 104
- 108
-
4Great code, and let's all consider the "general case," where the OP might want to automate a few dozen graphs of "animal[j] vs animal[k]" and call up a database of images to plot. GIMP/GraphicConverter/Photoshop might be easier for one graph, but automation always wins when doing 10^n (n>=1) graphs. – Carl Witthoft Oct 31 '12 at 11:25