自定义比例和间距排列ggplot图表

11
我正在尝试将n个条形图与一个共同的标签绘图组合在一起。我的问题是grid.arrange将两个图表组合成50%-50%。我正在寻找像布局矩阵这样的东西,您可以在其中指定4个插槽,前3个被第一个图占用,最后一个插槽被第二个图占用。并根据绘图数量进行类似的自定义。下面是我正在尝试的示例代码:
#load libraries
require(ggplot2)
require(reshape)
require(grid)
require(gridExtra)

#data creation
#DATA
temp<-data.frame(var1=sample(0:100,100,replace=T))
temp$var2<-100-temp$var1
temp$type<-factor(c(rep("S1",50),rep("S2",50)))
temp$label<-factor(rep(1:50,2))
temp1<-melt(temp,id.var=c("type","label"))
#LABELS
labs1<-data.frame(pos=c(1,8,22,45,50))
labs2<-data.frame(pos1=round((diff(labs1$pos)/2)+labs1$pos[1:length(labs1$pos)-1],1),
         lab=c("A","B","D","E"))

#plots
plot1<-ggplot(data=temp1)+
geom_bar(aes(x=label,y=value,fill=variable),stat="identity",space=0,width=1)+
facet_grid(type~.)+theme_bw()+labs(x=NULL,y=NULL)+
scale_y_continuous(expand=c(0,0))+
theme(legend.position="none",axis.text=element_blank(),axis.ticks=element_blank())
plot2<-ggplot()+
geom_line(data=labs1,aes(x=pos,y=-0.05),size=0.6)+
geom_point(data=labs1,aes(x=pos,y=-0.05))+labs(x=NULL,y=NULL)+
geom_text(data=labs2,aes(x=pos1,y=-0.1,label=lab))+
theme_bw()+scale_x_continuous(expand=c(0,0))+scale_y_continuous(limit=c(-0.5,0))+
theme(legend.position="none",axis.text=element_blank(),axis.ticks=element_blank())

plot3<-grid.arrange(plot1, plot2)
#here perhaps there is a way to say plot1 to take up 1/3 of the plot area.

两个图表并不完全对齐,但这是另一个问题。这很有用。 如何使用grid.arrange排列任意数量的ggplots? 我可以逐个绘制每个图形,但我想要有facet标签。

你的代码无法运行。在语句labs2<- data.frame(pos1<- round...中,没有 lab$pos。此外,我认为你想要的是 pos1= round(... 而不是 pos1<- round(... - jlhoward
如果您将“labs”更改为“labs1”并添加“gridExtra”,则可以正常工作。 - agstudy
抱歉,现在已经修复了。 - mindlessgreen
2个回答

23
grid.arrange(plot1, plot2, widths=c(0.7, 0.3), ncol=2)

很抱歉,针对您的例子:

grid.arrange(plot1, plot2, heights=c(0.7, 0.3), nrow=2)

编辑 - 关于图表之间的间距:

blank<-rectGrob(gp=gpar(col="white")) # make a white spacer grob
grid.arrange(plot1, blank, plot2, heights=c(0.7, 0.05, 0.25), nrow=3)

1
我认为你想要 heights=c(0.3,0.7) 或者 heights=c(0.33, 0.67) - jlhoward
啊,高度。是的。谢谢。还有控制排列图之间间距的参数吗? - mindlessgreen
2
@Roy 更新了代码,演示了如何在绘图之间添加间隔。如果您想更改图表在插槽中的行为,您需要使用theme()编辑图表边距等。 - Troy

9

使用grid.arrange()无法正确对齐面板,最好使用gtable进行操作。

require(gtable)

g1 <- ggplotGrob(plot1)
g2 <- ggplotGrob(plot2)
## add dummy column for missing strips
g2 <- gtable_add_cols(g2, unit(0,"mm"))
## merge, basing widths on g1
g <- gtable:::rbind_gtable(g1, g2, "first")
## add spacing
g <- gtable_add_rows(g, unit(1,"cm"), pos=nrow(g1))
grid.newpage()
grid.draw(g)

这里输入图片描述

请注意,使用这种策略,默认情况下面板高度是相等的。这是因为它们在布局(g$heights)中出现为unit(1, "null")。如果需要其他比例,可以轻松编辑g$heights


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接