Custom legend with imported images

Viewed 1457

I'm currently creating plots in ggplot2 by importing custom images and using them as geom_points, similar to this post, except I am looping through different images for unique levels of a factor.

Is there an easy way to add these images to the legend? I've seen multiple posts on custom legends in ggplot2, but nothing that deals with imported images.

2 Answers

Using html tags with element_markdown, you can specify anything you want in your legend.

Assuming that you have a png image in a file, that this file is located in a certain folder having a filename image, then you can run, for example:

p = ggplot(mtcars, aes(mpg, disp, colour = factor(vs))) + 
    geom_point() +
    theme(legend.key.size = unit(1, "cm"))
labels <- c()
labels[1]=paste0("<img src='", folder, image, ".png' width='16' />")
labels[2]="<strong>Faces</strong>"
p + theme(legend.text = element_markdown(color = "black", size = 11)) + 
scale_color_manual(name = "factor(vs)", labels = labels, , values = c(1,2))

will return this: enter image description here

Related