Search code examples
rggplot2time-series

change x limits of gg_season plot


Let's say I have this plot and I want the x limits to be ["January", "August"], I would I go about it?

Code and picture credits to Forecasting: Principles and Practice (3rd ed)

library(fpp3)

PBS |>
  filter(ATC2 == "A10") |>
  select(Month, Concession, Type, Cost) |>
  summarise(TotalC = sum(Cost)) |>
  mutate(Cost = TotalC / 1e6) -> a10

a10 |>
  gg_season(Cost, labels = "both") +
  labs(y = "$ (millions)",
       title = "Seasonal plot: Antidiabetic drug sales")

enter image description here


Solution

  • The gg_season() plot helper is intended to provide a common time series plot with some flexibility, without being a general purpose plotting function.

    To plot a subsets of the seasonal period, you may find it easier to create the plot yourself. Here's an example of how this can be done.

    library(fpp3)
    
    PBS |>
      filter(ATC2 == "A10") |>
      select(Month, Concession, Type, Cost) |>
      summarise(TotalC = sum(Cost)) |>
      mutate(Cost = TotalC / 1e6) -> a10
    
    a10 |>
      filter(month(Month) %in% 1:8) |> 
      ggplot(aes(x = month(Month), y = Cost, colour = factor(year(Month)))) + 
      geom_line() +
      geom_text(
        aes(label = year(Month)), 
        data = a10 |> group_by(year(Month)) |> filter(month(Month) == min(month(Month))),
        hjust = 1
      ) +
      scale_x_continuous(breaks = 1:8, labels = month.abb[1:8]) +
      guides(colour = "none") +
      labs(y = "$ (millions)",
           title = "Seasonal plot: Antidiabetic drug sales")
    

    Created on 2023-05-06 with reprex v2.0.2