【问题标题】:Adjust space between gridded, same-sized ggplot2 figures调整网格,相同大小的 ggplot2 图形之间的空间
【发布时间】:2015-06-04 14:26:31
【问题描述】:

我正在尝试将多个 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

【问题讨论】:

    标签: r ggplot2 gridextra


    【解决方案1】:

    您已将“宽度”设置为两个图的最大值。这意味着“花瓣宽度”图的 y 轴宽度将与“萼片宽度”图的 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)
    

    【讨论】:

    • 所以这部分代码[, -(1:3)], size = "first") 正在删除第二个绘图的y 轴和左边距?然后gt$widths 正在确定 cbinded 绘图的列宽?
    • @nofunsally,正确无误。可以随时使用gtable_show_layout (x)检查布局。