1
votes

I'm trying to use cowplot package's draw_image() function. I've managed to get an image in a graph as an example.

I can't work out how the xy locations work, I had to keep inputting random numbers until I got to see the image.

require(ggplot2) #required packages
require(cowplot)
require(magick)

p1 <- qplot(Sepal.Length, Sepal.Width, data = iris)

ggdraw(p1) +      
  draw_image(
    "https://upload.wikimedia.org/wikipedia/en/7/77/EricCartman.png",
    y = 0.2,
    scale = 0.5
  )

Can anyone advise on what scale they function? It sure doesn't seem to be the same scale as the graph.

1

1 Answers

3
votes

It's in the coordinates of the plot. The point that may be confusing you is that ggdraw() is setting up a new coordinate system running from 0 to 1 in both x and y. If you want to draw an image in the plot coordinates, there's no need to use ggdraw(). Just add draw_plot() directly to the plot.

library(ggplot2)
library(cowplot)
theme_set(theme_bw())

p1 <- qplot(Sepal.Length, Sepal.Width, data = iris)

# ggdraw() sets up a new coordinate system running from 0 to 1. This
# allows you to place an image on top of the plot.
ggdraw(p1) + 
  draw_image("https://upload.wikimedia.org/wikipedia/en/7/77/EricCartman.png")

# if you want to draw the image into the plot, don't use ggdraw()
p1 + draw_image(
  "https://upload.wikimedia.org/wikipedia/en/7/77/EricCartman.png",
  x = 5, y = 2.5, width = 2, height = 1.5
)

Created on 2018-12-19 by the reprex package (v0.2.1)