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

Pandas DatetimeIndex绘图设置每小时次网格、每6小时主网格的方法

实现DatetimeIndex x轴双样式网格线的方法

你原来的代码通过which='both'将主次x轴网格统一设置为了虚线,只需要拆分主次网格的配置逻辑,额外定义6小时间隔的主刻度,再分别设置对应网格样式即可,完整可运行的修改后代码如下:

import pandas
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
plt.rcParams.update({'figure.figsize': [15, 8],
                     'font.family': 'sans-serif',
                     'font.sans-serif': 'Verdana',
                     'font.size': 13,
                     'legend.frameon': True,
                     'legend.framealpha': 0.9,
                     'legend.facecolor': "white",
                     'legend.edgecolor': "black"})

d = pandas.DataFrame({"A": [x for x in range(12)], "B": [6 for x in range(12)]})
d.index = pandas.date_range("2021-01-01", "2021-01-01 11:00:00", freq="H")
ax = d.plot()

# 原有次刻度(1小时间隔)配置
xtick_minor = pandas.date_range(start=d.index.min(), end=d.index.max(), freq='H')
ax.set_xticks(xtick_minor, minor=True)

# 新增主刻度(6小时间隔)配置
xtick_major = pandas.date_range(start=d.index.min(), end=d.index.max(), freq='6H')
ax.set_xticks(xtick_major, minor=False)

# 分别配置主次网格样式
ax.grid('on', which='major', axis='x', linestyle="-", linewidth=1.2)
ax.grid('on', which='minor', axis='x', linestyle="--", linewidth=0.8)

plt.show()

逻辑说明

  • matplotlib的x轴刻度分为major(主)、minor(次)两个独立层级,网格样式可以分别对两个层级配置
  • 用freq='6H'生成间隔6小时的时间序列作为主刻度,绑定到minor=False的主刻度层级
  • 分别设置主网格为实线、次网格为虚线,也可以按需调整linewidth参数修改线条粗细区分层级

内容的提问来源于stack exchange,提问作者d.b

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:27:04