【问题标题】:Multiple plots side by side - How to make all plots the same widths? [duplicate]多个图并排 - 如何使所有图的宽度相同? [复制]
【发布时间】:2018-01-25 07:51:45
【问题描述】:

我只是安排三个 ggplots 以便它们在保存的 png 中并排显示。因此,我遵循了this answer 的有用线索。为了更清楚,我只显示最右边的图例。从逻辑上讲,由于图例,现在必须为最右边的图指定更大的宽度。使用scales::arrangeGrob(),我们可以实现这一点,例如c(600, 600, 750)

library(ggplot2)
economics$long <- with(economics, ifelse(uempmed > 8.61, 1, 0))
p <- ggplot(economics[economics$date < "1979-01-01", ], 
            aes(date, unemploy, color = long)) + 
  geom_line() + theme(legend.position="none")
q <- ggplot(economics[economics$date < "1991-01-01", ], 
            aes(date, unemploy, color = long)) + 
  geom_line() + theme(legend.position="none")
r <- ggplot(economics[economics$date < "2003-01-01", ], 
            aes(date, unemploy, color = long)) +
  geom_line()

l <- list(p, q, r)

library(gridExtra)
ggsave("test.png", 
       arrangeGrob(grobs = l, nrow = 1, ncol = 3, 
                   widths = c(600, 600, 750), heights = NULL, 
                   padding = unit(0.5, "line")),
       width = 18, height = 9, units = "cm", dpi = 600,
       scale = 1.5)

我确信通过反复试验,我可以调整最右边的情节,直到它适合为止。实际的问题是,尽管600 的值相同,但中间和最左边的图的宽度不匹配,这真的很烦人:

有人知道如何使所有地块的宽度相同吗?

【问题讨论】:

  • 我想如果你有相同的x轴范围,它应该可以解决问题+ xlim(range(economics$date))
  • 如果你不想改变比例,你可以使用ggarrange from egg: egg::ggarrange(p, q, r, nrow = 1)
  • @headpoint 我看不到任何效果。
  • 请测试一下:figure &lt;- egg::ggarrange(p, q, r, nrow = 1); ggsave("~/myStocks.pdf", figure, width = 22, height = 9, units = "cm", dpi = 600)
  • library(patchwork); p + q + r。从github安装。

标签: r ggplot2 grob r-egg


【解决方案1】:

一种可能的解决方案是通过@baptise 使用包egg

# Using OPs data/plots
# Add aligned plots into a single object 
figure <- egg::ggarrange(p, q, r, nrow = 1)
# Save into a pdf
ggsave("~/myStocks.pdf", figure, width = 22, height = 9, units = "cm", dpi = 600)

对齐后的结果如下:

【讨论】:

    猜你喜欢
    • 2011-06-10
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多