你如何在 ggplot2 中为刻面添加通用标签? [英] How do you add a general label to facets in ggplot2?

查看:25
本文介绍了你如何在 ggplot2 中为刻面添加通用标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常有分面的数值.我希望提供足够的信息来解释补充标题中的这些分面值,类似于轴标题.labeller 选项会重复很多不必要的文本,并且无法用于较长的可变标题.

I often have numeric values for faceting. I wish to provide sufficient information to interpret these faceting values in a supplemental title, similar to the axis titles. The labeller options repeat much unnecessary text and are unusable for longer variable titles.

有什么建议吗?

默认:

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)

我喜欢什么:

我在 ggplot 中能做的最好的:

The best I can do in ggplot:

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

正如@Hendy 所指出的,类似于:向 ggplot2 绘图添加辅助 y 轴 - 制作完美

As indicated by @Hendy, similar to: add a secondary y axis to ggplot2 plots - make it perfect

推荐答案

由于最新的ggplot2内部使用了gtable,修改一个图很容易:

As the latest ggplot2 uses gtable internally, it is quite easy to modify a figure:

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)

当然,你可以写一个自动添加条状标签的函数.ggplot2 的未来版本可能会有这个功能;不过不确定.

Of course, you can write a function that automatically add the strip labels. A future version of ggplot2 may have this functionality; not sure though.

这篇关于你如何在 ggplot2 中为刻面添加通用标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆