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

如何在Python Matplotlib折线图中设置X轴时间间隔与格式并修正代码

修正Matplotlib X轴刻度设置的问题

你原来的代码里X轴刻度设置的写法有误,plt.xticks是用于直接设置刻度值的函数,并不是坐标轴对象,所以没法直接调用.set_major_locator和.set_major_formatter方法。另外还要注意几个细节:一是要确保你的DataFrame索引是datetime类型(不然日期刻度的设置不会生效),二是dfMax变量需要先定义才能用在plt.yticks里。

下面是修正后的完整代码:

import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 读取CSV数据
df = pd.read_csv(
    "Data 8199 2391 6_6_2019 13_39_02.csv",
    sep="\t",
    skiprows=68,
    encoding="utf-16",
    index_col=0
)

# 关键步骤1:将索引转换为datetime类型(否则日期刻度设置无效)
df.index = pd.to_datetime(df.index)

# 定义y轴刻度的最大值(根据你的数据实际情况调整)
dfMax = df.max().max()

# 获取当前坐标轴对象
ax = plt.gca()

# 关键步骤2:设置X轴每15分钟一个主刻度
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=15))

# 关键步骤3:设置X轴刻度显示格式为%d-%H:%M
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%H:%M'))

# 设置y轴刻度
plt.yticks(np.arange(20, dfMax, step=5))

# 自动旋转X轴标签,避免重叠(可选但实用)
plt.xticks(rotation=45)

plt.show()

几个重要说明:

  • 必须把DataFrame的索引转换成datetime类型:如果你的原始索引是字符串格式的日期,mdates的定位器和格式化器根本没法识别,所以这一步是前提。
  • 使用plt.gca()获取当前坐标轴:这是Matplotlib中操作坐标轴属性的标准方式,之后通过ax.xaxis来操作X轴的刻度设置。
  • 可选的plt.xticks(rotation=45):当X轴标签较多时,旋转标签可以避免互相重叠,提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:17:45