I am currently following along with Forecasting: Principles and Practice, 3rd Edition, which is graciously available
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 yearmonth
s. How can I get a more detailed x-axis under these circumstances?
CodePudding user response:
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")
CodePudding user response:
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)