我试图在R中使用ggplot2和gridExtra构建一个5 x 6的绘图矩阵。为了简单起见,我可以用2×2矩阵和一些假数据来展示我的问题。使用gridExtra时一致的绘图面板宽度/高度
#Load libraries
library(ggplot2); library(gridExtra)
#Data
data = rbind(data.frame(x=rnorm(100,0,1),ALP='A',NUM=1),data.frame(x=rnorm(100,20000,1000),ALP='A',NUM=2),data.frame(x=rnorm(100,100,10),ALP='B',NUM=1),data.frame(x=rnorm(5000,1000),ALP='B',NUM=2))
#Ggplot2 facet_grid
ggplot(data,aes(x=x,y=..scaled..,fill='red')) + geom_density() + facet_grid(ALP~NUM,scales='free') + guides(fill=FALSE)
结果不好看,作为X-规模是整个小面的标签如此不同。我试图用gridExtra手动完成它。
#Assemble grobs
plt1 = ggplot(subset(data,ALP=='A'&NUM==1),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + facet_grid(.~NUM,scales='free') + guides(fill=FALSE) + theme(axis.title.x=element_blank(),axis.title.y=element_blank())
plt2 = ggplot(subset(data,ALP=='A'&NUM==2),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + facet_grid(ALP~NUM,scales='free') + guides(fill=FALSE) + theme(axis.text.y=element_blank(),axis.ticks.y=element_blank(),axis.title.y=element_blank(),axis.title.x=element_blank())
plt3 = ggplot(subset(data,ALP=='B'&NUM==1),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + guides(fill=FALSE) + theme(axis.title.x=element_blank(),axis.title.y=element_blank())
plt4 = ggplot(subset(data,ALP=='B'&NUM==2),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + facet_grid(ALP~.,scales='free') + guides(fill=FALSE) + theme(axis.text.y=element_blank(),axis.ticks.y=element_blank(),axis.title.y=element_blank(),axis.title.x=element_blank())
#Plot it out
grid.arrange(plt1,plt2,plt3,plt4,nrow=2,ncol=2,left=textGrob("scaled",rot=90,vjust=1),bottom=textGrob("x"))
我几乎没有,可惜在上,右上角的绘图板(X,Y)是比所有其他较小。同样,左下角的绘图面板(x,y)比其余的都要大。我希望所有的绘图面板(x,y)都是相同的高度/宽度。我发现了一些使用gtable的代码,但它似乎只在grobs没有facet标签时才能正常工作。当行数/列数增加时,效果更加夸张。
最简单的办法是使用'facet_wrap(尺度=“免费”)' – baptiste
@baptiste我真的不喜欢使用facet_wrap(的样子),因为我有很多方面的。哦,我想这已经够好了。谢谢! – user13317