多个地块并排 - 如何使所有地块的宽度相同?

时间:2018-01-25 07:51:46

标签: r ggplot2 grob r-egg

我只是安排了三个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的值相同,但中间和最左边的图的宽度不匹配,这真的很烦人:

enter image description here

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

1 个答案:

答案 0 :(得分:2)

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

# 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)

对齐结果如下:

enter image description here