r - 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')
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')
解决方案
推荐阅读
- wordpress - Wordpress 访问日志中的不间断 GET 请求
- javascript - 将颜色值 onclick 从黑色增加到红色 Javascript
- java - 与嵌入式 tomcat 交战
- python - 带有“w”参数的 Python 日志记录配置文件
- opencv3.0 - 使用opencv提取前景
- amazon-web-services - 使用什么从 OpenFIGI API 获取数据以存储到 AWS 或 Snowflake?
- flutter - 导航时未定义的命名“上下文”
- verilog - 如何解决verilog模块实例化错误
- vbscript - 在 VBscript 中删除文件
- c++ - 在执行 glDrawElements 期间,nvoglv32.dll 中的 OpenGL 崩溃