patchwork: how to align plots vertically?

Consider this simple example


library(tidyverse)
library(lubridate)
library(patchwork)


df1 <- tibble(time = c(ymd_hms('2019-10-01 10:00:00.123'),
                       ymd_hms('2019-10-01 10:01:00.123'),
                       ymd_hms('2019-10-01 10:02:00.123'),
                       ymd_hms('2019-10-01 10:03:00.123')),
              value = c(1,2,3,4))


df2 <- tibble(time = c(ymd_hms('2019-10-01 10:02:00.123'),
                       ymd_hms('2019-10-01 10:03:00.123'),
                       ymd_hms('2019-10-01 10:04:00.123')),
              value = c(20, 30, 40))


p1 <- df1 %>% ggplot(aes(x = time, y = value)) + geom_line()

p2 <- df2 %>% ggplot(aes(x = time, y = value)) + geom_line()

p1/p2

this gives

However, I would like the plots to be aligned on the x axis. Is that possible?

Thanks!

bind_rows(df1 %>% mutate(df = 1),
          df2 %>% mutate(df = 2)) %>% 
  ggplot(aes(x = time, y = value)) +
  geom_line() +
  facet_wrap(~df, ncol = 1, scale = "free_y")

Hope it helps :slightly_smiling_face:

2 Likes

I was just typing up a very similar solution.

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
# library(patchwork)


df1 <- tibble(time = c(ymd_hms('2019-10-01 10:00:00.123'),
                       ymd_hms('2019-10-01 10:01:00.123'),
                       ymd_hms('2019-10-01 10:02:00.123'),
                       ymd_hms('2019-10-01 10:03:00.123')),
              value = c(1,2,3,4))


df2 <- tibble(time = c(ymd_hms('2019-10-01 10:02:00.123'),
                       ymd_hms('2019-10-01 10:03:00.123'),
                       ymd_hms('2019-10-01 10:04:00.123')),
              value = c(20, 30, 40))

dftog <- bind_rows(df1, df2, .id="Plot")

dftog %>%
  ggplot(aes(x=time, y=value)) +
  geom_line() +
  facet_grid(Plot~.)

Created on 2019-12-02 by the reprex package (v0.3.0)

1 Like

thanks! so I guess patchwork is not useful in this setup