insert image in caption and adjust its size to fontsize

时间:2019-04-08 13:54:13

标签: r ggplot2 grid gtable

Problem

I would like to insert an image in between some text in the caption of my ggplot.

What I found on sofar is this solution using some gtable hacking. But this solution is somewhat unviable for me, because I want to add text before and after the image. Besides, it doesn't resize the image to the actual fontsize of the caption.

library(tidyverse)
library(magick)
library(grid)
library(gtable)

ggplot(iris, 
       aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  theme(plot.caption = element_text(hjust=0, 
                                    size = 10)) +
  labs(caption = "\uA9 *INSERT MY COMPANY LOGO HERE* My fabulous company, 2019")

without my logo

my_logo <- image_read("https://upload.wikimedia.org/wikipedia/commons/3/3e/Phalaenopsis_JPEG.png")
print(my_logo)

this is the logo I want o insert

Goal

What I want to achieve is this. Note that the logo's (my_logo) vertical size is equal to the fontsize of the caption.

enter image description here

1 个答案:

答案 0 :(得分:1)

您链接的答案提供了所有要素,

library(ggplot2)
library(grid)
library(dplyr)
library(gtable)

lg <- textGrob(label = "\uA9", x = unit(0, "npc"), just = "left")
rg <- textGrob(label = "My fabulous company, 2019", x = unit(0, "npc"), just = "left")
mg <- png::readPNG(system.file("img", "Rlogo.png", package="png")) %>%
  rasterGrob(interpolate = TRUE, height = grobHeight(rg))

p <- ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  labs(caption="") # to create space for title

# convert to grob
gt <- ggplotGrob(p)

# create new title as a tableGrob with separate cells for image & text
new.title <- gtable_row('caption', grobs = list(lg,mg,rg),
                        widths = unit.c(grobWidth(lg), grobWidth(mg), unit(1,"null")), 
                        height=unit(1,"null")) %>%
  # optional: adda fixed amt of space between image & text
  gtable_add_col_space(width = unit(5, "pt")) 

# assign new title back to gt
gt$grobs[[which(gt$layout$name == "caption")]] <- new.title

grid.newpage()
grid.draw(gt)