Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align x axis with grid.arrange

Tags:

r

ggplot2

I'm trying to plot two aligned graphics, but one of them has a label and of them doesn't.

Example:

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
)

Result:

enter image description here

Is there a way to align the axis without using facet_wrap? (I want to add specific label formatters for each plot because they are in different units and facet_wrap doesn't allow me to do that as far as I know)

like image 344
gsmafra Avatar asked Oct 27 '25 07:10

gsmafra


1 Answers

You can manage them as different plots, with same legend, using cowplot package:

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

like image 137
s__ Avatar answered Oct 28 '25 21:10

s__



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!