gpt4 book ai didi

r - 如何在 ggplot2 中向构面添加通用标签?

转载 作者:行者123 更新时间:2023-12-03 05:14:44 25 4
gpt4 key购买 nike

我经常使用数值进行分面。我希望提供足够的信息来解释补充标题中的这些分面值,类似于轴标题。贴标机选项会重复许多不必要的文本,并且无法用于较长的变量标题。

有什么建议吗?

默认值:

test<-data.frame(x=1:20, y=21:40, facet.a=rep(c(1,2),10), facet.b=rep(c(1,2), each=20))
qplot(data=test, x=x, y=y, facets=facet.b~facet.a)

enter image description here

我想要什么:

enter image description here

我在 ggplot 中能做的最好的事情:

qplot(data=test, x=x, y=y)+facet_grid(facet.b~facet.a, labeller=label_both)

enter image description here

正如@Hendy 所指出的,类似于: add a secondary y axis to ggplot2 plots - make it perfect

最佳答案

由于最新的ggplot2内部使用了gtable,因此修改图形非常容易:

library(ggplot2)
test <- data.frame(x=1:20, y=21:40,
facet.a=rep(c(1,2),10),
facet.b=rep(c(1,2), each=20))
p <- qplot(data=test, x=x, y=y, facets=facet.b~facet.a)

# get gtable object
z <- ggplotGrob(p)

library(grid)
library(gtable)
# add label for right strip
z <- gtable_add_cols(z, unit(z$widths[[7]], 'cm'), 7)
z <- gtable_add_grob(z,
list(rectGrob(gp = gpar(col = NA, fill = gray(0.5))),
textGrob("Variable 1", rot = -90, gp = gpar(col = gray(1)))),
4, 8, 6, name = paste(runif(2)))

# add label for top strip
z <- gtable_add_rows(z, unit(z$heights[[3]], 'cm'), 2)
z <- gtable_add_grob(z,
list(rectGrob(gp = gpar(col = NA, fill = gray(0.5))),
textGrob("Variable 2", gp = gpar(col = gray(1)))),
3, 4, 3, 6, name = paste(runif(2)))

# add margins
z <- gtable_add_cols(z, unit(1/8, "line"), 7)
z <- gtable_add_rows(z, unit(1/8, "line"), 3)

# draw it
grid.newpage()
grid.draw(z)

enter image description here

当然,您可以编写一个自动添加 strip 标签的函数。 ggplot2 的 future 版本可能具有此功能;但不确定。

关于r - 如何在 ggplot2 中向构面添加通用标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11353287/

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