Search code examples
rdataframeggplot2facetfacet-wrap

ggplot using facet_wrap of multiple data.frame in R?


I am trying to ggplot D2 on the same figure as of D1. I, however, do not have data for the Variable X in D2 data.frame. How i can plot D2 on its respective facets of D1 plot? these plots represent data for 2011 and 2014 so i would like to have legends for the line to differentiate which line represent which year data.

library(tidyverse)

set.seed(1500)

D1 <- data.frame(Day = 1:8, A = runif(8, 2,16), S = runif(8, 3,14), X = runif(8, 5,10), Z = runif(8, 1,12), Year = rep("2011",8))
D2 <- data.frame(Day = 1:8, A = runif(8, 2,14), S = runif(8, 1,13),  Z = runif(8, 3,14), Year = rep("2014",8))

# plotting D1
 D1 %>% gather(-c(Day, Year), key = "Variable", value = "Value") %>% 
  ggplot( aes(x = Day, y = Value))+
  geom_line()+facet_wrap(~Variable,  scales = "free_y", nrow=2)

# Plotting D2 on top ?

Solution

  • How about convert two DFs to long format then merge them together before plotting?

    library(tidyverse)
    
    set.seed(1500)
    
    D1 <- data.frame(Day = 1:8, A = runif(8, 2,16), S = runif(8, 3,14), 
                     X = runif(8, 5,10), Z = runif(8, 1,12), Year = rep("2011",8))
    D1_long <- D1 %>% 
      pivot_longer(-c(Day, Year),
                   names_to = 'Variable',
                   values_to = 'Value')
    
    D2 <- data.frame(Day = 1:8, A = runif(8, 2,14), S = runif(8, 1,13),  
                     Z = runif(8, 3,14), Year = rep("2014",8))
    D2_long <- D2 %>% 
      pivot_longer(-c(Day, Year),
                   names_to = 'Variable',
                   values_to = 'Value')
    
    ### merge two data frames
    DF <- bind_rows(D1_long, D2_long)
    
    my_linetype <- setNames(c("dashed", "solid"), unique(DF$Year))
    
    # plot DF
    DF %>% 
      ggplot(aes(x = Day, y = Value, 
                 color = Year,
                 linetype = Year))+
      geom_line() +
      facet_wrap(~ Variable,  scales = "free_y", nrow = 2) +
      scale_color_brewer(palette = 'Dark2') +
      scale_linetype_manual(values = my_linetype) +
      theme_bw(base_size = 14) +
      theme(legend.position = 'bottom') +
      theme(legend.key.size = unit(2.5, 'lines'))
    

    Created on 2020-07-15 by the reprex package (v0.3.0)