如何在ggplot2中为facet添加常规标签?

时间:2012-07-05 22:15:37

标签: r label facet 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))
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

3 个答案:

答案 0 :(得分:45)

由于最新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

当然,您可以编写一个自动添加条带标签的功能。未来版本的ggplot2可能具有此功能;但不确定。

答案 1 :(得分:1)

除了kohske概述的方法之外,您还可以通过更改

为添加的框添加边框
col=NA

col=gray(0.5), linetype=1

另外,更改

fill=gray(0.5)

fill=grey(0.8)

gp=gpar(col=gray(1))

gp=gpar(col=gray(0))

如果您希望新条形图与构面标签匹配

z <- gtable_add_grob(z, 
      list(rectGrob(gp = gpar(col = gray(0.5), linetype=1, fill = gray(0.8))),
      textGrob("Variable 1", rot = -90, gp = gpar(col = gray(0)))),
      4, 8, 6, name = paste(runif(2)))

答案 2 :(得分:1)

可能有更好的方法,但你可以:

fac1 = factor(rep(c('a','b'),10))
fac2 = factor(rep(c('a','b'),10))
data = data.frame(x=1:10, y=1:10, fac1=fac1, fac2=fac2)
p = ggplot(data,aes(x,y)) + ggplot2::geom_point() + 
facet_grid(fac1~fac2)
p + theme(plot.margin = unit(c(1.5,1.5,0.2,0.2), "cm"))
grid::grid.text(unit(0.98,"npc"),0.5,label = 'label ar right', rot = 270) # right
grid::grid.text(unit(0.5,"npc"),unit(.98,'npc'),label = 'label at top', rot = 0)   # top