【问题标题】:Align x axis with grid.arrange将 x 轴与 grid.arrange 对齐
【发布时间】:2019-02-12 12:33:36
【问题描述】:

我正在尝试绘制两个对齐的图形,但其中一个有标签,而另一个没有。

例子:

library(dplyr)
library(ggplot2)

df <-
  seq(as.Date("2019-01-01"), as.Date("2019-01-31"), by = 1) %>%
  as_tibble() %>%
  rename(day = value) %>%
  mutate(
    x = seq(1, 31, by = 1),
    y = x * 2 - 20
  )

p1 <-
  df %>%
  gather(key, value, c(x, y)) %>%
  ggplot(aes(x = day, y = value, color = key)) +
  geom_line(size = 1)

p2 <-
  df %>%
  ggplot(aes(x = day, y = y / x)) +
  geom_line(size = 1)

grid.arrange(
  p1, p2
)

结果:

有没有办法在不使用 facet_wrap 的情况下对齐轴? (我想为每个绘图添加特定的标签格式化程序,因为它们在不同的单位中,并且据我所知 facet_wrap 不允许我这样做)

【问题讨论】:

  • 从第一次绘图中删除图例是一个选项吗?在第二个情节中添加一个图例怎么样?
  • 这是一个我想避免的选项(除非我们可以在第二个情节创建一个完全空白的图例)
  • 如何将图例放在不同的位置,例如。 theme(legend.position="bottom")?
  • 由于 y 轴标签,当我这样做时,这些图仍未完全对齐。

标签: r ggplot2


【解决方案1】:

您可以使用cowplot 包将它们管理为具有相同图例的不同图:

library(cowplot)
legend <- get_legend(p1)   # get the legend of the first one plot

# here the plots in a grid
prow <- plot_grid( p1 + theme(legend.position="none"),
           # here you add the percentage
           p2 + theme(legend.position="none")+ scale_y_continuous(labels = scales::percent),
           align = 'v',
           labels = c("A", "B"),
           hjust = -1,
           nrow = 2)

# here you add the legend
p <- plot_grid( prow, legend, rel_widths = c(3, .3))
p

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多