Time Series multiple boxplots

Hi. I have been trying to create quarterly box plot for a time series data set for each year and have been unable to do it so far. I am aiming to create side by side boxplot for each quarter per year.
Qtr1 Qtr2 Qtr3 Qtr4
1960 5387 6211 6659 5983
1961 5709 6458 6875 6162
1962 6098 7075 7595 6882
1963 6707 7874 8555 7503
1964 7469 8829 9513 8415
1965 8270 9503 10306 9077

generated the above quarterly data using another time series data set:
elec_quarterly = aggregate.ts(mycbe, nfrequency = 4, FUN = sum)

What is the best way to proceed to get the required boxplots?

Hi @tdheer, this would be my approach (please next time provide you data in a copy-paste-safe way!):

Hope this is what you're looking for.

library(tibble)
library(dplyr)
library(tidyr)
library(ggplot2)

# create dataframe
d <- tribble(
  ~year, ~Qtr1, ~Qtr, ~Qtr3, ~Qtr4,
  "1960", "5387", "6211", "6659", "5983",
  "1961", "5709", "6458", "6875", "6162",
  "1962", "6098", "7075", "7595", "6882",
  "1963", "6707", "7874", "8555", "7503",
  "1964", "7469", "8829", "9513", "8415",
  "1965", "8270", "9503", "10306", "9077"
) %>% 
  mutate_all(as.numeric) # make all values numeric

# transform dataframe to long format
d_long <- d %>% 
  pivot_longer(
    cols = -year,
    names_to = "quarter",
    values_to = "n"
  ) 

# boxplot for each quarter, aggregating across years
ggplot(d_long, aes(quarter, n)) +
  geom_boxplot()

This code generates something like this:

1 Like

I'll keep you advice in mind next time thanks :slightly_smiling_face: .

However the data I copied here is far less than what I have. Using tribble in that case won't be feasible as i have the data for almost 75 years!

1 Like

That is just for the purpose of making a reproducible example, you are not supposed to do that, you have to use your own data instead. Read this reprex guide to understand the concept.

1 Like

No problem @tdheer! The code should work in the complete dataframe. Let us know if it does the job. :grin:

It worked. :slight_smile:
However I found a shorter way as well:

cycle(elec_quarterly)
boxplot(elec_quarterly ~ cycle(elec_quarterly)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.