3

So, I want to add a logo footer to my ggplot, but I want to do so via a function that I can use the + operator with, so I can do: qplot(1:10, 1:10) + add_mylogo()

I can get what I want with this:

library(magick)
library(ggplot2)
mylogo <- image_scale(image_read("https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png"), "180")
qplot(1:10, 1:10) + labs(caption="")
grid::grid.raster(mylogo, x = .97, y = .02, just = c('right', 'bottom'), width = unit(1.2, 'inches'))

Which produces:

enter image description here

My problem is that I want to use + to add it to the plot.

So then I tried this:

library(cowplot)
library(magick)
library(ggplot2)
mylogo <- image_scale(image_read("https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png"), "380")
qplot(1:3, 1:3)+ labs(caption="") +
  draw_image(mylogo, x=3, y = .2, hjust=.7, vjust=0, scale = .5, clip=TRUE)

Which produces:

enter image description here

So now I have it working with a + operator, but I can't figure out how to use any sort of relative positioning. I saw this post about relative positioning using annotate and tried it, but it doesn't work

qplot(1:3, 1:3)+ labs(caption="") +
  draw_image(mylogo, x = -Inf, y = Inf, hjust=.7, vjust=0, scale = .5, clip=TRUE)
Error in if (rasterRatio > vpRatio) { : 
  missing value where TRUE/FALSE needed

So the first option using grid works with relative positioning, but not with the + operator, and the second option using cowplot works with the + operator, but not relative positioning. Is there any way to get both?

cory
  • 6,529
  • 3
  • 21
  • 41

2 Answers2

6

You could consider using ggtext:

library(ggplot2)
library(ggtext)
qplot(1:3, 1:3) +
  labs(caption = "<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png' width='100'/>") +
  theme(plot.caption = element_markdown())

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
0

The way you are using draw_image is intended to use the plot coordinates, not relative positioning, as you can see in the draw_image help examples. For using relative positioning you have to change a little bit your code, adding first the image, and then the plot inside a draw_plot call:

ggdraw() +
  draw_image(mylogo, scale = 0.2, x = 0.38, y = -0.45) +
  draw_plot(
    qplot(1:3, 1:3)+ labs(caption="") +
      theme(panel.background = element_blank(), plot.background = element_blank())
  )

log_test

In my tests, positioning seems to be relative to the center of the plot (x = 0, y = 0), so you need negative values to go down in y or left in x. Another "problem" is that the logo is added before, so you must convert the plot or panel background to transparent or remove them.

MalditoBarbudo
  • 1,815
  • 12
  • 18