将图片添加到ggplot标题

8
我想在ggplot标题中添加图片或svg。

enter image description here

这就是我所追求的:

enter image description here

获取眼睛 "这里"

以下是我最好的尝试。

我不满意它,因为我必须尝试很多次才能将其放置在正确的位置。并非真正的通用解决方案。

library(ggplot2)
library(raster)
library(grid)

img1 <- as.matrix(raster(system.file("external/rlogo.grd", package="raster")))
img1[img1>128] <- NA
img1[img1>0] <- 0
image(img1)

g1 <- rasterGrob(img1, interpolate=TRUE)

p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + 
  ggtitle("       <- dat rLogo tho") +
  annotation_custom(g1,xmin = 1.2,1.6,35.5,38)

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)


  

你可以尝试使用emojifont包吗? - jmk
那是个好主意。但是1. 对我不起作用。"在grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x$y, : invalid input 'ðŸ˜' in 'utf8towcs'"。2. 表情符号太有趣了,我需要认真的眼神。 - Andre Elrico
1个回答

5

下面是我试着使用看起来很严肃的眼睛png图标

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

eyeImg <- png::readPNG("serious_eye.png") %>%
  rasterGrob(interpolate = TRUE)

p <- ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  ggtitle("") # 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(widths = grobWidth(gt),
       heights = grobHeight(gt)) %>%
  gtable_add_grob(grobs = eyeImg, t = 1, l = 1) %>%
  gtable_add_cols(widths = unit(1, "null")) %>%
  gtable_add_grob(textGrob(label = "<- very serious eye",
                           x = unit(0, "npc"), just = "left"),
                  t = 1, l = 2) %>%
  # optional: adda fixed amt of space between image & text
  gtable_add_col_space(width = unit(5, "pt")) 

# dev.off(); grid.draw(new.title)

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

grid.draw(gt)

plot


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接