Search code examples
rggplot2timeserieschart

ggplot2: Add secondary x label (year below months)


My Problem is related to: Axis labels on two lines with nested x variables (year below months)

However, my data looks a little different.

library(dplyr)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", 
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

I would like my line graph too look like this, but without the vertical line if possible:

enter image description here


Solution

  • library(tidyverse)
    
    #data:
    set.seed(122)
    df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
    #> Warning: Calling `as_tibble()` on a vector is discouraged, 
    #> because the behavior is likely to change in the future. 
    #> Use `tibble::enframe(name = NULL)` instead.
    
    df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", 
                      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)
    
    df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)
    
    #solution:
    month_lab <- rep(unique(df$month), length(unique(df$year)))
    
    year_lab <- unique(df$year)
    
    df %>%
      as.data.frame() %>%
      rename(price = 1) %>% 
      mutate(rnames = rownames(.)) %>% 
      ggplot(aes(x = as.numeric(rnames), y = price, 
                 group = year)) +
      geom_line() +
      labs(title = "Stock Price Chart", y = "Price", x = "date") +
      scale_x_continuous(breaks = seq(1, 1260, by = 21), 
                         labels = month_lab, expand = c(0,0)) +
      facet_grid(~year, space="free_x", scales="free_x", switch="x") +
      theme(strip.placement = "outside",
            strip.background = element_rect(fill=NA,colour="grey50"),
            panel.spacing=unit(0,"cm"))
    

    ![](https://i.imgur.com/QnCsmNd.png)

    Created on 2019-05-28 by the reprex package (v0.3.0)