将图像添加到ggplot标题 [英] Adding image to ggplot title
本文介绍了将图像添加到ggplot标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在ggplot标题中添加图片或svg.
I want to add an image or svg to the ggplot title.
这是我的目标:
"此处 "
我对它不满意,因为我必须尝试很多错误才能使其正确定位.并不是一个通用的解决方案.
I'm unhappy with it because I have to try and error a lot to get it into the right position. not really a general solution.
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)
推荐答案
这是我尝试使用非常严重的尝试眼的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)
这篇关于将图像添加到ggplot标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文