cowplot: shared legend (two line plot)

In the following example, how do I narrow the gap between the plots and legend? And, how do I change the location of the legend -- left, right, and middle ? Thanks!

library(tidyverse)
library(cowplot)
#> Warning: package 'cowplot' was built under R version 4.0.3
###########
# Data
###########
set.seed(123)
toy_data <- tibble(
  year = rep(2008:2017, times = 2),
  delay_type = rep(c("A", "B"),each = 10),
  mean = rnorm(20, mean = 50 , sd = 20),
  median = rnorm(20, mean = 40, sd = 15)
) %>% 
  pivot_longer(
    cols = mean:median,
    names_to = "stats",
    values_to = "delay"
  ) %>% 
  mutate(number_obs = rep(100:109, each = 4),
         sd = rep(1:10, each = 2, times = 2)) #updated sd

######################
#  Plot1
######################
# x-axis breaks and labels
x <- toy_data %>%
  filter(delay_type == "A") %>% 
  arrange(year) %>% 
  distinct(breaks=year, labs=paste0(year, " (n=",number_obs,")"))
# Plot
plot1 <- toy_data %>% 
  filter(delay_type == "A") %>% 
  ggplot(aes(x = year, y = delay , color = stats)) +
  geom_line(size=0.3, alpha=0.5) +
  geom_text(aes(label=round(delay)), show.legend=FALSE, size=2.8) +
  labs(
    subtitle = "Yearly Stat A",
    color = "Statistics",
    y = "Delay",
    x = "Year"
  ) +
  # Breaks and Labels
  scale_x_continuous(breaks = x$breaks, labels=str_wrap(x$labs,5)) +
  theme_bw() +
  theme(text = element_text(size = 9)) +
  guides(colour=guide_legend(override.aes=list(size=2, alpha=1)))

######################
#  Plot2
######################
# x-axis breaks and labels
x <- toy_data %>%
  filter(delay_type == "B") %>% 
  arrange(year) %>% 
  distinct(breaks=year, labs=paste0(year, " (n=",number_obs,")"))
# Plot
plot2 <- toy_data %>% 
  filter(delay_type == "A") %>% 
  ggplot(aes(x = year, y = delay , color = stats)) +
  geom_line(size=0.3, alpha=0.5) +
  geom_text(aes(label=round(delay)), show.legend=FALSE, size=2.8) +
  labs(
    subtitle = "Yearly Stat B",
    color = "Statistics",
    y = "Delay",
    x = "Year"
  ) +
  # Breaks and Labels
  scale_x_continuous(breaks = x$breaks, labels=str_wrap(x$labs,5)) +
  theme_bw() +
  theme(text = element_text(size = 9)) +
  guides(colour=guide_legend(override.aes=list(size=2, alpha=1))) +
  theme(legend.position= "top")


##########
# COWPLOT
##########
# extract the legend from one of the plots
legend_yearly <- get_legend(plot2)

# Option 1
plot_grid(plot1  + theme(legend.position="none"),
          plot2 + theme(legend.position="none"),
          legend_yearly)

# Option 2
plot_grid(plot1  + theme(legend.position="none"),
          plot2 + theme(legend.position="none"),
          legend_yearly, nrow = 3)          

Created on 2020-11-20 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.