Search code examples
rdataframeggplot2facet-wrapgeom

ggplot using facet_wrap in R?


I want to use the face_wrap functionality of ggplot to draw the following example data. The plot doesn't seem right. The line should have smooth connection with no extra space in both facets (ie Facet A has empty space from 10-15 while Facet B has space 0-5). Also the months on the x-axis is a bit odd.

library(tidyverse)
library(lubridate)


set.seed(555)

D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                      A = runif(1095, 0,10), Z = runif(1095, 5,15))
D %>% pivot_longer(-Date, names_to = "Variable", values_to = "Value") %>% 
  mutate(Year = year(Date), Month = month(Date)) %>% 
  ggplot(aes(x = Month, y = Value, col = as.factor(Year)))+
  geom_line()+facet_wrap(~Variable, nrow = 2)

enter image description here

Desired Output: I am looking for a plot like below where the lines have smooth month to month connection. enter image description here


Solution

  • If you want to use the day of year as your x-position and still get a valid date axis, you could un-year your date:

    library(tidyverse)
    library(lubridate)
    #> 
    #> Attaching package: 'lubridate'
    #> The following object is masked from 'package:base':
    #> 
    #>     date
    
    
    set.seed(555)
    
    D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2003-12-31"), by="day"),
                    A = runif(1095, 0,10), Z = runif(1095, 5,15))
    D %>% pivot_longer(-Date, names_to = "Variable", values_to = "Value") %>% 
      mutate(Year = year(Date), Month = month(Date),
             Date = {year(Date) <- 2000; Date}) %>%
      ggplot(aes(x = Date, y = Value, col = as.factor(Year)))+
      geom_line()+facet_wrap(~Variable, nrow = 2) +
      scale_x_date(date_breaks = "1 month", 
                   date_labels = "%b")
    

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