2015-06-04 77 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)'檢查佈局。 –

相關問題