求助:在R中绘制含年份与季度坐标轴的时间序列图表
使用R绘制季度时间序列目标样式图表
我们可以用ggplot2配合lubridate、dplyr实现你需要的季度时间序列图表,以下是完整实操方案:
1. 加载必备工具包
library(ggplot2) library(lubridate) library(dplyr)
2. 准备/处理数据
先模拟一组季度时间序列数据(你直接替换成自己的真实数据即可):
set.seed(123) df <- tibble( date = seq(as.Date("2018-01-01"), as.Date("2022-12-31"), by = "quarter"), value = rnorm(20, mean = 50, sd = 8) ) %>% mutate( year = year(date), quarter = quarter(date, with_year = FALSE), quarter_label = paste0("Q", quarter) )
3. 绘制分年度对比的季度图表(匹配目标样式核心逻辑)
这种分面布局能清晰对比每一年的季度趋势,和你提供的目标图结构一致:
ggplot(df, aes(x = quarter_label, y = value, group = year, color = factor(year))) + geom_line(linewidth = 1) + geom_point(size = 3) + # 按年份拆分面板,每个年份单独展示季度数据 facet_wrap(~year, scales = "free_x", nrow = 1) + # 自定义标签与标题 labs( x = "季度", y = "数值", color = "年份", title = "季度时间序列趋势对比" ) + theme_minimal() + theme( strip.text = element_text(size = 12, face = "bold"), axis.text.x = element_text(angle = 0, hjust = 0.5), legend.position = "bottom" )
如果需要将所有年份的季度放在同一轴连续展示,可使用以下代码:
df <- df %>% mutate(year_quarter = paste(year, quarter_label, sep = "-")) ggplot(df, aes(x = year_quarter, y = value, group = 1, color = factor(year))) + geom_line(linewidth = 1) + geom_point(size = 3) + labs( x = "年份-季度", y = "数值", color = "年份", title = "季度时间序列整体趋势" ) + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1), legend.position = "bottom" )
你可以根据目标图的视觉风格,调整color、linewidth、theme等参数,比如更换配色、调整坐标轴样式等。
内容的提问来源于stack exchange,提问作者Axel Arce
相关产品推荐
相关产品推荐

