将x轴与grid.arrange对齐

4
我正在尝试绘制两个对齐的图形,但其中一个有标签,另一个没有。
示例:
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不允许我这样做)

最初的回答:


从第一个图中删除图例是一种选择吗?在第二个图中添加图例呢? - user2974951
这是一个我想避免的选项(除非我们可以在第二个图中创建一个完全空白的图例)。 - gsmafra
把图例放在不同的位置怎么样,比如 theme(legend.position="bottom") - user2974951
当我这样做时,由于y轴标签,图形仍然没有完全对齐。 - gsmafra
添加空的图例 https://dev59.com/ZZ_ha4cB1Zd3GeqPy3bw? - user2974951
1个回答

4
您可以使用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

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接