Axel Arce
Axel Arce

Reputation: 1

Axis of a plot with quarters and year

Im working with time series given in quarter in R and I want to make a graph as follows:

enter image description here

I have search all over the internet but I haven't get any answer

Upvotes: 0

Views: 196

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174576

If you have a time series object like this:

d <- ts(c(265, 280, 288, 280, 278, 292, 298, 282), start = 2016, frequency = 4)

d
#>      Qtr1 Qtr2 Qtr3 Qtr4
#> 2016  265  280  288  280
#> 2017  278  292  298  282

Then you could get a reasonable replica of the plot by doing:

library(ggplot2)

data.frame(date = time(d), SALES = d) |>
  within(year <- floor(date)) |>
  within(Quarter <- paste0("Q", date %% 1 * 4 + 1)) |>
  ggplot(aes(interaction(Quarter, year), SALES, group = 1)) +
  geom_line(linewidth = 2, color = "#497dba") +
  scale_y_continuous("PRICE (millions)", labels = scales::dollar,
                     breaks = 24:31 * 10, limits = c(240, 310)) +
  scale_x_discrete(NULL, labels = ~sub("\\.", "\n", .x)) +
  theme_classic(base_size = 20)

Created on 2023-02-19 with reprex v2.0.2

Upvotes: 1

Related Questions