2

I'm trying to find a way to insert an image into the corner of a ggplot panel, without specifying the coordinates manually each time.

In this instance, I'm attempting to place a graphic in the top right.

library(magick)
library(ggplot2)
library(datasets)

homer <- magick::image_read("http://icons.iconarchive.com/icons/jonathan-rey/simpsons/128/Homer-Simpson-04-Happy-icon.png")


g <- ggplot(mpg, aes(class)) +
  geom_bar() +
  labs(
    title = "Count of Auto by Class",
    subtitle = "Text to Create More Space")

g + annotation_custom(rasterGrob(homer, interpolate = TRUE),
                      xmax = Inf, ymax = Inf) +
  coord_cartesian(clip = "off")

I have found some examples that come close to solving this:

Inserting an image to ggplot outside the chart area

Corner Labels in ggplot2

But neither quite get there. Specifying the exact location at which to place the image seems to require quite a bit of trial-and-error on each plot created, especially when x is categorical.

I would also like to maintain the size of my original image; the code I've used above seems to stretch it across the plot.

Thanks in advance...much appreciated.

Tung
  • 26,371
  • 7
  • 91
  • 115

1 Answers1

0

try this

library(grid)
a <- rasterGrob(homer, interpolate = TRUE, 
                width=unit(1,'cm'),
           x = unit(1,"npc"), y = unit(1,"npc"),
           hjust = 1, vjust=1)

g + annotation_custom(grob = a) 
  • add some explanation – Marek Urbanowicz Jul 23 '18 at 06:12
  • Thanks! I'm actually looking to place this outside the chart area, but that can be accomplished by adjusting hjust/vjust and setting `coord_cartesian(clip = "off")`. Now if I could just figure out how to keep my image from blurring ever so slightly... – troy_barnes Jul 24 '18 at 14:18