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

Julia中如何更改Plots绘图X轴日期的精度?

问题:如何调整Plots绘图中X轴日期刻度为月度或季度精度?

我使用以下代码绘制了日期序列的折线图,但默认的X轴日期刻度精度过高,希望将其改为月度或季度刻度,请问该如何实现?

using DataFrames
using StatsPlots
using Plots
using Dates

dates = Date(2021, 1, 1):Day(1):Date(2023, 3, 28)
n = length(dates)

df = DataFrame(
  date=dates,
  col1=rand(n),
  col2=rand(n)
)

@df df plot(
  :date, cols(2:3),
  legend=:outerright,
  xlabel="Date",
  ylabel="Val",
  title="Test plot",
  size=(1000, 600),
  dpi=300,
  left_margin=5Plots.mm,
  bottom_margin=5Plots.mm,
)

默认日期刻度的折线图


解决方案

1. 设置为月度刻度

通过自定义xticks参数,生成每月起始日期的序列,并指定刻度标签的格式化规则:

# 生成月度起始日期序列
dates_monthly = Date(2021,1,1):Month(1):Date(2023,3,1)

@df df plot(
  :date, cols(2:3),
  legend=:outerright,
  xlabel="Date",
  ylabel="Val",
  title="Test plot (Monthly Ticks)",
  size=(1000, 600),
  dpi=300,
  left_margin=5Plots.mm,
  bottom_margin=5Plots.mm,
  # 设置X轴刻度:位置+格式化标签
  xticks=(dates_monthly, Dates.format.(dates_monthly, "yyyy-MM"))
)

如果需要更贴合中文场景的格式,可改用自定义格式化函数:

xticks=(dates_monthly, d -> Dates.format(d, "yyyy年MM月"))

若出现标签重叠问题,可添加旋转参数优化显示:

xticks=(dates_monthly, Dates.format.(dates_monthly, "yyyy-MM"), rotation=45)

2. 设置为季度刻度

生成季度起始日期序列后,配置对应刻度标签:

# 生成季度起始日期序列(每年1、4、7、10月的第一天)
dates_quarterly = Date(2021,1,1):Quarter(1):Date(2023,1,1)

@df df plot(
  :date, cols(2:3),
  legend=:outerright,
  xlabel="Date",
  ylabel="Val",
  title="Test plot (Quarterly Ticks)",
  size=(1000, 600),
  dpi=300,
  left_margin=5Plots.mm,
  bottom_margin=5Plots.mm,
  # 刻度标签显示为"Q1 2021"格式
  xticks=(dates_quarterly, d -> "Q$(Dates.quarterofyear(d)) $(Dates.year(d))")
)

关键说明

  • 利用Dates模块的Month(1)/Quarter(1)生成间隔序列,确保刻度覆盖整个绘图时间范围;
  • 通过Dates.format()或自定义匿名函数,可灵活控制刻度标签的显示格式;
  • 若刻度密度仍不符合需求,可手动指定刻度位置数组,比如只保留每年的1月和7月刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:17:21