R 按自定义比率和间距将GG图排列在一起

R 按自定义比率和间距将GG图排列在一起,r,ggplot2,gridextra,R,Ggplot2,Gridextra,我试图将n个条形图与底部的一个公共标签图结合起来。我的问题是grid.arrange以50%-50%的比例组合了两个图。我正在寻找类似布局矩阵的东西,在这里你可以指定4个插槽,前3个插槽由第一个绘图占用,最后一个插槽由第二个绘图占用。并根据绘图数量进行类似的自定义 我这里有一个我正在尝试的示例代码: #load libraries require(ggplot2) require(reshape) require(grid) require(gridExtra) #data creation

我试图将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.
#加载库
需要(ggplot2)
需要(重塑)
需要(网格)
需要(额外)
#数据创建
#资料
临时雇员
很抱歉给你举个例子:

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)
blankgrid.arrange()无法正确对齐面板,最好使用GTTable

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)
require(gtable)

g1我想你想要
heights=c(0.3,0.7)
,或者
heights=c(0.33,0.67)
aah heights。对谢谢还有控制排列图之间间距的参数吗?@Roy更新以显示如何在两个图之间放置间隔符。如果要更改插槽中的绘图行为,则需要使用theme()编辑绘图页边距等。您的代码不会运行。在语句中,
labs2如果按labs1更改labs并添加
gridExtra
,则会起作用。对此表示抱歉。现在修好了。
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)