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? 我可以一一绘制,但我想要刻面标签。

4

2 回答 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)
于 2014-02-03T14:37:05.577 回答
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)

在此处输入图像描述

请注意,默认情况下,此策略的面板高度相等。那是因为它们出现unit(1, "null")在布局 ( g$heights) 中。g$heights如果需要另一个比率,编辑起来很简单。

于 2014-02-03T15:33:02.613 回答