Is it possible to add an image to ggplot chart which will be outside chart area?
I know it is possible to add images to the chart using annotate_raster and annotate_custom, however they both add images inside the chart. I need to add company logo in the upper right corner above the chart - at the title level.
Example of adding image using annotate_custom: Inserting an image to ggplot2
UPDATE: Following recommendations from user1317221_G, I'm able to put image outside.
library(png)
library(grid)
library(ggplot2)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img, interpolate=TRUE)
plt <- qplot(1:10, 1:10, geom="blank") +
opts(title = 'Title') +
geom_point()
plt2 <- plt + annotation_custom(g, xmin=9, xmax=10, ymin=10.5, ymax=11.25)
gt <- ggplot_gtable(ggplot_build(plt2))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
i would like to put image automatically - determine xmin/xmax and ymin/ymax automatically. Using traditional graphics i can call par('usr') and get chart parameters, but this is not applicable to ggplot charts. Is there an easy way to determine plot area in ggplot? For example get sizes of plt and plug the values for limits into plt2
UPDATE2: This method also doesn't really work if you use faceting. For example I would like to put logo in the right corner at title level, in the following chart, and I get errors if I use method above.
d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) +
stat_binhex(na.rm = TRUE) +
labs(title = 'Title') +
theme(aspect.ratio = 1) +
facet_wrap(~ color, scales = "free_x")
See Question&Answers more detail:os