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

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

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

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

目标是让“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,"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)之间空格的方法,我将不胜感激。 我的方法是调整 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",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,.rows = structure(list(
    1:3),ptype = integer(0),class = c("vctrs_list_of","vctrs_vctr","list"))),-1L),class = c("tbl_df","tbl","data.frame"),.drop = TRUE),class = c("grouped_df","tbl_df","data.frame"))
yhfhr8100 回答:通过 grid_arrange 将 Text_Grob 与 ggplot 结合 - 删除 Text_grob-Margins

这是一个更简单的示例,展示了如何使用 {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 年 7 月 29 日创建

本文链接:https://www.f2er.com/19714.html

大家都在问