How to get a more detailed x-axis when plotting a tsibble?
Asked Answered
I

2

5

I am currently following along with Forecasting: Principles and Practice, 3rd Edition, which is graciously available online. To replicate my issue, you will need to install and then load the package fpp3. You will then need to carry out the following in R (or RStudio):

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

After defining a10, it will then be necessary to plot the tsibble, like so:

autoplot(a10, Cost) +
  labs(y = "$ (millions)",
       title = "Australian antidiabetic drug sales")

You should then get a plot like this:

tsibble plot with somewhat faulty x-axis

It's fine for the most part, but I would like to have at least twice as many ticks on the x-axis, possibly more if they can be rotated by 45° or so. I tried something that seemed promising which was adding scale_x_date(date_labels = "%m-%Y") to the plot object but that only works with objects of class Date and here we are dealing with yearmonths. How can I get a more detailed x-axis under these circumstances?

Irena answered 6/10, 2021 at 19:35 Comment(0)
C
3

One way could be changing the class of Month to class date and applying scale_x_date():

a10 %>% 
  mutate(Month = as.Date(Month)) %>% 
  ggplot(aes(x=Month, y=Cost)) + 
  geom_line() +
  scale_x_date(date_breaks = "1 year")

enter image description here

Conclude answered 6/10, 2021 at 20:11 Comment(1)
You're a literal heroIrena
J
6

You can change the x axis scale for a yearmonth() using scale_x_yearmonth(). This also applies to other date types like yearquarter() and yearweek().

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

autoplot(a10, Cost) +
  labs(y = "$ (millions)",
       title = "Australian antidiabetic drug sales") + 
  scale_x_yearmonth(date_breaks = "1 year", date_labels = "%Y")

Created on 2021-10-07 by the reprex package (v2.0.1)

Jackass answered 6/10, 2021 at 22:3 Comment(0)
C
3

One way could be changing the class of Month to class date and applying scale_x_date():

a10 %>% 
  mutate(Month = as.Date(Month)) %>% 
  ggplot(aes(x=Month, y=Cost)) + 
  geom_line() +
  scale_x_date(date_breaks = "1 year")

enter image description here

Conclude answered 6/10, 2021 at 20:11 Comment(1)
You're a literal heroIrena

© 2022 - 2024 — McMap. All rights reserved.