我正在尝试将多个ggplot2图表排列到一个输出/网格中。我希望这些图(不考虑标签)大小相同。我找到了办法this,但现在我想调整地块之间的空间。
例如:
在这个图中,我想减少两个图之间的空间。我尝试过调整边距,删除刻度等等。这已经消除了一些空间。
有没有办法在这些情况下更好地控制绘图之间的间距调整?
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
答案 0 :(得分:2)
您已设置&#39;宽度&#39;成为两个地块的最大值。这意味着“花瓣宽度”的y轴宽度。绘图将与&#39; Sepal Widths&#39;的y轴宽度相同。情节。
调整间距的一种方法是首先将两个凹槽合并为一个布局,删除第二个图的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)