通过 grid_arrange 将 Text_Grob 与 ggplot 组合 - 删除 Text_grob-Margins

Combining Text_Grob with ggplot via grid_arrange - delete Text_grob-Margins

一段时间以来,我一直在尝试将 TextGrob 与 ggplot 合并。不幸的是,TextGrob 总是与情节产生一定的距离,这是我不想要的。

查看当前结果时,整个事情变得更加清晰:

目标是将“Lennart”直接放在图上,作为一种人工轴标签。

目前的代码是这样的:(我稍微调整了格式,但要点应该是可以识别的)

png("PNGZwischenspeicher2.png", bg = "transparent", width = 2500, height = 1000)
p <- ggplot(DBE3, aes(x = reorder(emoji, n), y = n,reorder(emoji,-n)))+
  theme(plot.margin = margin(0,0,0,0, "pt"))+
  geom_col(alpha = 0.2, width = 0.2)+
  coord_flip()+
  theme(axis.title.y = element_blank())+
  scale_fill_manual(values=c("transparent", "transparent", "transparent"))+
  scale_y_continuous(expand = expansion(mult = c(0.00, .5)))
print(p)
dev.off()
img2 <- readPNG("PNGZwischenspeicher2.png")
PE2 <- rasterGrob(img2)

Header2 <- textGrob("Lennart", rot = 90, gp = gpar(fontsize = 12, fontface = 'plain'))
grid.arrange(Header2, PE2, nrow = 1)

不要问为什么需要通过 png-workaround 编辑绘图,否则当前脚本不允许这样做:D

如果有人知道如何删除 text_grob 和图(或 png)之间的 space,我将不胜感激。 我的方法是调整 text_grob 的大小,但遗憾的是我还没有找到可行的方法。

非常感谢,祝您晚上愉快!


娱乐所需数据:

dput(DBE3)
structure(list(author = structure(c(1L, 1L, 1L), .Label = c("Lennart", 
"Toni Janina", "Toni"), class = "factor"), emoji = c("<U+0001F607>", 
"<U+0001F64F>", "<U+0001F605>"), n = c(90L, 47L, 30L), name = c("smiling face with halo", 
"folded hands", "grinning face with sweat"), hex_runes = c("1F607", 
"1F64F", "1F605"), hex_runes1 = c("1F607", "1F64F", "1F605"), 
    emoji_url = c("https://abs.twimg.com/emoji/v2/72x72/1f607.png", 
    "https://abs.twimg.com/emoji/v2/72x72/1f64f.png", "https://abs.twimg.com/emoji/v2/72x72/1f605.png"
    )), row.names = c(NA, -3L), groups = structure(list(author = structure(1L, .Label = c("Lennart", 
"Toni Janina", "Toni"), class = "factor"), .rows = structure(list(
    1:3), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", 
"list"))), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"))

这是一个更简单的示例,展示了如何使用 {ggpp}(或 {ggpmisc})将 textGrob 添加到 ggplot。这也可以用 geom_text() 来完成,但我想你有一些比实际问题更复杂的东西。此代码可用于任何 grob,包括位图。

library(ggpp)
#> Loading required package: ggplot2
#> 
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#> 
#>     annotate
library(grid)

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  annotate(geom = "grob", x = 5, y = 40, 
           label = textGrob("Lennart", rot = 90, gp = gpar(fontsize = 12, fontface = 'plain')))

reprex package (v2.0.0)

于 2021-07-29 创建