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

如何使用Matplotlib自动格式化并均匀分布X轴日期刻度?

解决Matplotlib日期X轴刻度拥挤问题

问题背景

我一直在找用Python 3搭配Matplotlib实现日期均匀分布的方法,但没找到适配纯datetime对象列表场景的方案。需要绘制的时间跨度从几分钟到几周不等,日期是字符串格式的datetime,希望Matplotlib能自动格式化日期,让X轴刻度均匀分布、适配时间范围且不拥挤。

原代码

# imports
import csv
import matplotlib.pyplot as plt
import datetime

# store rows
rows = []

# read data
with open('weatherSoilData.csv', newline='') as csvFile:
    reader = csv.reader(csvFile, delimiter=',')
    for row in reader:
        rows.append(row)

# get rid of header
rows.pop(0)

# create column lists
dates = []
soilTemperatures = []

# loop through columns and create lists of the column values
for i in range(2):
    # handle dates
    if not i:
        for row in rows:
            dates.append(row[i])
    else:
        for row in rows:
            soilTemperatures.append(float(row[i]))

# display data
plt.plot(dates, soilTemperatures)
plt.title("Time vs. Soil Temperature")
plt.xlabel("Time")
plt.ylabel("Soil Temperature (degrees C)")
plt.xticks(rotation=90)
plt.ylim(-30, 50)
plt.show()

CSV文件片段

date,soilTemperature(degrees C)
2023-09-25 17:38:48.761035,21.375
2023-09-25 17:38:51.562840,21.375
2023-09-25 17:38:54.362466,21.375
2023-09-25 17:38:57.161336,21.312
2023-09-25 17:38:59.960572,21.312
2023-09-25 17:39:02.762784,21.375

当前问题

生成的图表X轴日期刻度过于拥挤,无法清晰阅读。


解决方案

核心问题是原代码中日期还是字符串格式,Matplotlib无法识别为时间序列,因此无法自动优化刻度。以下是修复后的代码:

优化后的代码

import csv
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator, AutoDateFormatter
import datetime

dates = []
soilTemperatures = []

# 读取CSV并转换数据格式
with open('weatherSoilData.csv', newline='') as csvFile:
    reader = csv.reader(csvFile, delimiter=',')
    next(reader)  # 跳过表头
    for row in reader:
        # 将日期字符串转换为datetime对象
        date_obj = datetime.datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S.%f")
        dates.append(date_obj)
        soilTemperatures.append(float(row[1]))

# 绘制图表
fig, ax = plt.subplots()
ax.plot(dates, soilTemperatures)

# 设置自动日期刻度和格式化
locator = AutoDateLocator(minticks=3, maxticks=10)  # 控制刻度数量范围
formatter = AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

# 自动旋转刻度标签避免重叠
fig.autofmt_xdate()

# 设置图表属性
ax.set_title("时间 vs. 土壤温度")
ax.set_xlabel("时间")
ax.set_ylabel("土壤温度 (摄氏度)")
ax.set_ylim(-30, 50)

plt.show()

关键改动说明

  • 转换日期格式:用datetime.datetime.strptime()把字符串转成datetime对象,让Matplotlib识别为时间轴
  • 自动刻度管理:使用AutoDateLocator和AutoDateFormatter,根据时间跨度自动选择合适的刻度间隔(比如分钟、小时、天),同时通过minticks和maxticks控制刻度数量,避免拥挤
  • 优化标签显示:fig.autofmt_xdate()自动旋转刻度标签,进一步避免重叠
  • 简化代码结构:直接在读取CSV时生成数据列表,去掉冗余的嵌套循环

这个方案能自动适配从几分钟到几周的时间跨度,保证X轴刻度均匀且清晰可读。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 14:44:51