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

问题描述 投票:70回答:3

我经常有刻面的数值。我希望提供足够的信息来解释补充标题中的这些分面值,类似于轴标题。贴标签选项重复了许多不必要的文本,并且对于较长的变量标题不可用。

有什么建议?

默认值:

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中做得最好:

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

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

r label facet ggplot2
3个回答
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)

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


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)))

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
© www.soinside.com 2019 - 2024. All rights reserved.