2015-06-04 74 views
2

我试图将多个ggplot2图组排列成一个输出/网格。我希望情节(不考虑标签)是相同的大小。我找到了一种方法来做this,但是现在我想调整两张图之间的空间。调整网格,相同大小的ggplot2数字之间的空间

例如: example plots with default spacing

在这个情节,我想,以减少两个地块之间的空间量。我尝试调整边距,删除滴答等,这已经删除了一些空间。

example plots with reduced space between plots

有没有一种方法来在诸如这些情况地块之间的间距调整的更多的控制权?

library(MASS) 
data(iris) 
library(ggplot2) 
library(grid) 
library(gridExtra) 

p1 <- ggplot(iris,aes(Species,Sepal.Width))+geom_violin(fill="light gray")+geom_boxplot(width=.1) +coord_flip() + 
    theme(axis.title.y = element_blank()) + ylab("Sepal Width") 

p2 <- ggplot(iris,aes(Species,Petal.Width))+geom_violin(fill="light gray")+geom_boxplot(width=.1) + coord_flip() + 
    theme(axis.title.y = element_blank(), axis.text.y=element_blank()) + ylab("Petal Width") 


p11 <- p1 + theme(plot.margin = unit(c(-0.5,-0.5,-0.5,-0.5),"mm")) 
p22 <- p2 + theme(plot.margin = unit(c(-0.5,-0.5,-0.5,-0.5),"mm"), axis.ticks.y=element_blank()) 


# https://stackoverflow.com/questions/24709307/keep-all-plot-components-same-size-in-ggplot2-between-two-plots 
# make plots the same size, even with different labels 
gl <- lapply(list(p11,p22), ggplotGrob) 
widths <- do.call(unit.pmax, lapply(gl, "[[", "widths")) 
heights <- do.call(unit.pmax, lapply(gl, "[[", "heights")) 
lg <- lapply(gl, function(g) {g$widths <- widths; g$heights <- heights; g}) 

# https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2-in-r?lq=1 
grid.arrange(lg[[1]],lg[[2]], ncol=2) #in gridExtra 

回答

2

您已将“宽度”设置为两个图的最大值。这意味着'Petal Widths'图的y轴的宽度将与'Sepal Widths'图的y轴的宽度相同。调整间隔

的一种方法是,首先,将两个grobs组合成一个布局,删除y轴和所述第二曲线的左边距:

# Your code, but using p1 and p2, not the plots with adjusted margins 
gl <- lapply(list(p1, p2), ggplotGrob) 
widths <- do.call(unit.pmax, lapply(gl, "[[", "widths")) 
heights <- do.call(unit.pmax, lapply(gl, "[[", "heights")) 
lg <- lapply(gl, function(g) {g$widths <- widths; g$heights <- heights; g}) 

# New code 
library(gtable) 
gt = cbind(lg[[1]], lg[[2]][, -(1:3)], size = "first") 

然后剩余的空间的宽度之间的两条曲线可以被调整:

gt$widths[5] = unit(2, "lines") 

# Draw the plot 
grid.newpage() 
grid.draw(gt) 
+0

因此,代码'的这个部分[, - (1:3)],大小=“第一”)'被删除的第二曲线图的y轴和左边距?然后'gt $ widths'确定了cbinded plot的列的宽度? – nofunsally

+0

@nofunsally,正确和正确。可以随时用'gtable_show_layout(x)'检查布局。 –

相关问题