【问题标题】:Reduce all plot margins in ggplot2 and grid.arrange减少 ggplot2 和 grid.arrange 中的所有绘图边距
【发布时间】:2019-01-11 11:43:21
【问题描述】:

我正在尝试用grid.arrange() 编译四个图表,并减少每个图表的边距,以便它们美观紧凑。我想使用theme(plot.margin=unit(c(x, x, x , x), "cm"))(欢迎使用其他解决方案)。

不久前有人问了一个类似的问题: here

但是,plot.margin 现在需要没有默认值的参数 units。我找不到任何关于 R 在这个论点中所期望的解释。有人能举个例子吗?

有关可重现的示例,请使用旧问题中提供的示例。 谢谢!

【问题讨论】:

    标签: r ggplot2 margins


    【解决方案1】:

    我们有unit(c(t, r, b, l), "cm"),其边距大小分别位于顶部、右侧、底部和左侧。而实际上还有一个默认值:

    theme_get()$plot.margin
    # [1] 5.5pt 5.5pt 5.5pt 5.5pt
    

    一个例子:

    qplot(mpg, wt, data = mtcars) + 
      theme(plot.margin = unit(c(5, 15, 25, 35), "pt"),
            plot.background = element_rect(fill = "grey90"))
    

    【讨论】:

    • 致 OP:记住顺序的有用助记符是 trouble。
    • 我意识到我的括号弄错了,R 向我显示了以下错误消息:Error in unit(c(0.1, 0.1, 0.1, 0.1)) : argument "units" is missing, with no default 因此,我认为unitunits 是两个不同的论点。 . 我的错。
    • @Mehdi.K,我明白了。碰巧你的问题还是有道理的,因为我相信这个theme_get()$plot.margin 不是很明显,也可能有用。
    【解决方案2】:

    您可以使用“cm”、“lines”或“points”作为单位参数。下面是一些示例代码。只需更改 theme(plot.margin=unit(c(x, x, x , 1.5), "lines") 中的最后一个参数,即可在开头对齐 3 个图形。

    library(ggplot2)
    library(grid)
    library(gridExtra)
    
    test1 <- qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.text=element_text(size=16),
    axis.title=element_text(size=18),axis.title.x=element_text(size=14),
    plot.margin = unit(c(1, 1, 0, 1.4), "lines"),
    legend.text=element_text(size=16))
    
    test2 <- qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.text=element_text(size=16),
    axis.title=element_text(size=18),axis.title.x=element_text(size=14),
    plot.margin = unit(c(1, 1, 0, 1.2), "lines"),
    legend.text=element_text(size=16))
    
    test3 <- qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.text=element_text(size=16),
    axis.title=element_text(size=18),axis.title.x=element_text(size=14),
    plot.margin = unit(c(1, 1, 0, 1), "lines"),
    legend.text=element_text(size=16)) 
    
    
    
    grid.arrange(test1,test2,test3, nrow=3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2017-06-09
      • 2011-05-01
      相关资源
      最近更新 更多