Vik G
Vik G

Reputation: 639

specifying x and y co-ordinates in annotate_custom in ggplot2

I created a barchart in ggplot2 using the following code.

g <- ggplot(mpg, aes(class))
# Number of cars in each class:
g + geom_bar()

I created an image object using the code such as

img <- png::readPNG("./watermark.png")
rast <- grid::rasterGrob(img, interpolate = T)

Now I am trying to paste this image onto the plot using a command such as

g + annotation_custom(rast, xmin=-Inf, xmax=Inf,ymin=-Inf,ymax=Inf)

which creates the following plot enter image description here https://i.sstatic.net/XdHBe.jpg

I understand that the x and y co-ordinates in annotation_custom are relative to the data plotted on the x and y axis.

In my case I have discrete data on the X Axis and want to paste this image in the top right corner, please can someone advise how I can do that.

Upvotes: 0

Views: 250

Answers (1)

mnm
mnm

Reputation: 2022

Although, not exactly the answer you are looking for, but do check these related answers, 1,2 and 3

library(grid)
library(png)
mypngfile <- download.file('http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Rlogo.png/200px-Rlogo.png', destfile = 'mypng.png', mode = 'wb')
mypng <- readPNG('mypng.png')
p + annotation_custom(rasterGrob(mypng))+
  geom_bar()

image-in-plot

Somehow, I cannot get annotation_raster to work with geom_bar().

Upvotes: 1

Related Questions