You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中将X轴日期格式化为季度(如2022-Q1)

问题

我使用ggplot2生成了如下图表,当前X轴为默认日期格式,请问是否可以将其格式化为季度形式(例如2022-Q1)?以下是我的数据与绘图代码:

data <- structure(list(Date = structure(c(19083, 19086, 19087, 19088, 
19089, 19090, 19093, 19094, 19095, 19096, 19101, 19102, 19103, 
19104, 19107, 19108, 19109, 19110, 19111, 19114, 19115, 19116, 
19117, 19118, 19121, 19122, 19123, 19124, 19125, 19128, 19129, 
19130, 19131, 19132, 19135, 19136, 19137, 19138, 19139, 19143, 
19144, 19145, 19146, 19149, 19150, 19151, 19152, 19153, 19156, 
19157, 19158, 19159, 19160, 19164, 19165, 19166, 19167, 19170, 
19171, 19172, 19173, 19174, 19178, 19179, 19180, 19181, 19184, 
19185, 19186, 19187, 19188, 19191, 19192, 19193, 19194, 19195, 
19198, 19199, 19200, 19201, 19202, 19205, 19206, 19207, 19208, 
19209, 19212, 19213, 19214, 19215, 19216, 19219, 19220, 19221, 
19222, 19223, 19226, 19227, 19228, 19229, 19230, 19233, 19234, 
19235, 19236, 19237, 19241, 19242, 19243, 19244, 19247), class = "Date"), 
    US = c(-0.099, -0.082, -0.102, -0.276, -0.265, -0.214, -0.254, 
    -0.321, -0.263, -0.195, -0.189, -0.077, -0.025, -0.278, -0.543, 
    -0.595, -0.638, -0.587, -0.571, -0.754, -0.681, -0.597, -0.68, 
    -0.738, -0.942, -0.882, -0.657, -0.673, -0.468, -0.394, -0.323, 
    -0.357, -0.604, -0.533, -0.409, -0.529, -0.577, -0.496, -0.344, 
    -0.362, -0.326, -0.367, -0.365, -0.318, -0.43, -0.405, -0.515, 
    -0.658, -0.77, -1.033, -1.058, -1.217, -1.112, -1.096, -1.114, 
    -1.158, -1.013, -0.915, -0.863, -1.099, -1.192, -1.236, -1.395, 
    -1.144, -1.09, -1.167, -1.325, -1.378, -1.343, -1.492, -1.591, 
    -1.56, -1.254, -1.505, -1.327, -1.505, -1.542, -1.528, -1.526, 
    -1.591, -1.416, -1.513, -1.577, -1.389, -1.429, -1.486, -1.547, 
    -1.649, -1.61, -1.585, -1.475, -1.393, -1.307, -1.376, -1.571, 
    -1.744, -2.067, -2.294, -2.401, -2.423, -2.449, -2.69, -2.633, 
    -2.654, -2.812, -2.909, -3.037, -2.912, -2.456, -2.523, -2.51
    )), row.names = c(NA, -111L), class = c("tbl_df", "tbl", 
"data.frame"))

library(tidyverse)

ggplot(data, aes(Date, US)) +
  geom_line(size=2) +
  scale_x_date(breaks = '3 months')
解决方案

可以直接通过scale_x_date()的labels参数指定季度格式,修改后的代码如下:

library(tidyverse)

ggplot(data, aes(Date, US)) +
  geom_line(size=2) +
  scale_x_date(breaks = '3 months', 
               labels = scales::date_format("%Y-Q%q"))

格式说明

  • %Y:代表4位完整年份(如2022)
  • %q:代表1-4的季度数字,和Q组合后就会生成2022-Q1这类格式

如果需要调整季度的显示样式,比如用罗马数字或者其他格式,可以修改格式符,不过上述写法已经满足你的需求。

内容的提问来源于stack exchange,提问作者Tanga94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:40:37