Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

ggplot2 - R ggplot geom_tile x axis year quarter labeling

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') 

enter image description here

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') 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...