Reputation: 1462
I have some time series data with quarterly frequency, as below.
I'm using geom_tile
to create a heatmap of these time series data, but the issue I have now is that the labeling on the x axis is defaulted to year eventhough the data is on quarterly.
My expectation was something like 2014 Q1
, 2020 Q4
as in the dataset.
set.seed(1990)
ID <- rep(c('A','B','C'),each = 84)
n <- rep(round(runif(84,1,4)), 3)
datetime <- rep(seq(as.POSIXct("2014-01-01"), as.POSIXct("2020-12-01"), by="month"), 3)
df <- tibble(ID,n, datetime)
df <- df %>%
#mutate(yearweek = tsibble::yearweek(datetime)) %>%
mutate(yearquarter = zoo::as.yearqtr(datetime)) %>%
#group_by(ID, yearweek) %>%
group_by(ID, yearquarter) %>%
summarise(n = sum(n))
df
ggplot(df
,
aes(y=ID,x= yearquarter,fill=n))+
geom_tile(color = 'gray')
Normally I can easily control the monthly level dataset with scale_x_date
as below but using it with quarterly data throws Error: Invalid input: date_trans works with objects of class Date only
.
I'm using tsibble::yearweek
to get weekly aggregation and zoo::as.yearqtr
for quarterly aggregation.
But the issue is when it comes to plotting, ggplot
may not support them. So is there a more consistent approach to dealing with time series data with multiple frequencies in R
/ggplot
?
scale_x_date(expand = c(0,0),breaks = seq(as.Date("2014-07-01"), as.Date("2020-12-01"), by = "1 month"), date_labels = "%Y %b", name = 'Monthly')
Upvotes: 0
Views: 1271
Reputation: 388797
Since you have zoo
's as.yearqtr
variable use zoo
's scale_x_yearqtr
to format the x-axis.
library(ggplot2)
ggplot(df,aes(y=ID,x= yearquarter,fill=n))+
geom_tile(color = 'gray') +
zoo::scale_x_yearqtr(format = '%Y Q%q')
Upvotes: 2