gpt4 book ai didi

r - 将图像添加到 ggplot 标题

转载 作者:行者123 更新时间:2023-12-02 05:33:32 31 4
gpt4 key购买 nike

我想将图像或 svg 添加到 ggplot 标题。

enter image description here

这就是我的目标:

enter image description here

吸引眼球“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)



最佳答案

这是我使用 very serious-looking eye 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

关于r - 将图像添加到 ggplot 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43472185/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com