Multiple variables in a sub plot using ggplot in R

Viewed 82

The code below plots multiple subplots for only one variable, but I want to create a multiple sub plots such that the first subplot will have first two variables (Barnwell_obs and Barnwell_sim) on the same plot. Similarly, second sub plot should contain the next two variables Breton_obs and Breton_sim, and so on. so basically, there will be two subplots from the data below. My actual data has more than 40 columns.

# Loading libraries

library(tidyverse)
library(lubridate)

df <- tribble(
  ~date, ~Barnwell_obs, ~Barnwell_sim,  ~Breton_obs, ~Breton_sim,
  
  "2013-01-01", 22.082, 90.86, 43.91,   110.36,
  "2013-02-02", 24.094, 80.86, 53.878,  115.36,
  "2013-03-03", 25.11,  80.86, 63.852,  120.36,
  "2013-04-04", 22.214, 70.86, 63.828,  130.36,
  "2013-05-05", 30.278, 70.86, 83.812,  140.36,
  "2013-06-06", 38.48,  60.86, 93.794,  130.36,
  "2013-07-07", 45.662, 70.86, 83.774,  130.36,
  "2013-08-08", 55.948, 80.86, 73.75,     120.36,
  "2013-09-09", 60.272, 91.14, 73.722,  120.36,
  "2013-10-10", 60.892, 91.14, 83.702,  110.36)
  

# Some quick data preparation

long_df <- df %>%
  mutate(date = ymd(date)) %>%
  pivot_longer(-date, names_to = "stations", values_to = "values")


# Simplified code

ggplot(long_df, aes(x = date, y = values)) +
  geom_line(size = 1) +
  scale_x_date("Month", 
               date_breaks = "month", 
               date_labels = '%B') +
  scale_y_continuous("Values", labels = function(x) paste0(x, "mm")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  facet_wrap(~ stations, ncol = 1)

1 Answers

pivot_longer is flexible, so we can make use of names_sep and names_to

library(dplyr)
library(tidyr)
long_df <- df %>% 
   pivot_longer(cols = -date, names_to = c(".value", 'grp'), names_sep = "_")
Related