【问题标题】:gridExtra panel plot with identical panel sizes in ggplotggplot中具有相同面板尺寸的gridExtra面板图
【发布时间】:2018-09-10 21:03:41
【问题描述】:
library(tidyverse)
library(grid)
df <- tibble(
  date = as.Date(40100:40129, origin = "1899-12-30"), 
  value = rnorm(30, 8)
  )

p1 <- ggplot(df, aes(date, value)) + 
  geom_line() + 
  scale_x_date(date_breaks = "1 day") + 
  theme(
    axis.title.x = element_blank(), 
    axis.text.x = element_text(angle = 90, vjust = 0.5)
  ) + 
  coord_cartesian(xlim = c(min(df$date) + 0, max(df$date) - 0))

p2 <- ggplot(df, aes(date, value)) + 
  geom_bar(stat = "identity") + 
  scale_x_date(date_breaks = "1 day") + 
  theme(
    axis.title.x = element_blank(), 
    axis.text.x = element_text(angle = 90, vjust = 0.5)
  ) + 
  coord_cartesian(xlim = c(min(df$date) + 0, max(df$date) - 0))

让我们创建图p1p1,如上所示。我可以将这些堆叠在一起,宽度完全相同(放大到全屏以使其明显)。请注意,日期排列完美。代码直接在下面。

grid.newpage()
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last"))

很遗憾,我不能在上面的代码块中使用ggsave(),所以我转到了 gridExtra 包。

gridExtra::grid.arrange(p1, p2)

这几乎可行,但请注意日期并没有完全对齐,以垂直方式比较顶部图表和底部图表。 那么... 什么相当于 rbind()s size = "last" 让我得到两个宽度完全相同的 grid.arrange'd 对象(这样日期才能正确排列)?

【问题讨论】:

    标签: r ggplot2 gridextra


    【解决方案1】:

    作为grid 的替代品,新的patchwork 库可能会有所帮助。它可以与 ggsave 一起使用,并且可以很好地对齐绘图。

    https://github.com/thomasp85/patchwork

    patchwork::plot_layout(p1 / p2)
    

    【讨论】:

      【解决方案2】:

      我发现了一个使用egg 包的解决方案,我认为它包含在ggplot2 中。我将走这条路线以防止必须安装patchwork。看来您需要 R 3.5+ 才能安装patchwork

      egg::ggarrange(p1, p2)
      p <- egg::ggarrange(p1, p2)
      ggsave(plot = p, "panel-plot.png")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多