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

如何重新设置Matplotlib图表X轴年份刻度,显示连续年份

解决Matplotlib时间轴显示连续年份的问题

问题核心

你的代码直接使用Excel读取的时间字符串绘图,Matplotlib会自动选择间隔刻度。要显示1996到2010的连续年份,需要将时间列转为datetime类型并手动指定X轴刻度,同时可优化冗余的站点切片代码。

修改后的完整代码

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

# 读取数据并预处理时间列
df = pd.read_excel("Julian_iski_data_python.xlsx")
# 将时间列转换为datetime类型,确保Matplotlib能正确解析时间轴
df["yyyy-mm-dd hh:mm:ss.sss"] = pd.to_datetime(df["yyyy-mm-dd hh:mm:ss.sss"])

# 筛选prSM=1的数据,按Station分组(替代逐个切片的冗余代码)
filtered_df = df[df["prSM [db]"] == 1]
station_groups = filtered_df.groupby("Station")

# 初始化绘图
fig = plt.figure(figsize=(12, 8))
axes = fig.add_axes([0.04, 0.06, 0.95, 0.91])

# 遍历每个站点绘图,自动分配标记和颜色
markers = ["ro", "b^", "gs", "md", "c*", "yp"]
for (station, group), marker in zip(station_groups, markers):
    axes.plot(group["yyyy-mm-dd hh:mm:ss.sss"], group["T(degC)"], marker, label=station)

# 设置X轴刻度:显示1996到2010的每一年
years = mdates.YearLocator()  # 每年生成一个刻度
years_fmt = mdates.DateFormatter("%Y")  # 刻度格式化为纯年份
axes.xaxis.set_major_locator(years)
axes.xaxis.set_major_formatter(years_fmt)

# 旋转X轴标签避免重叠
plt.xticks(rotation=45)

# 基础绘图设置
axes.set_xlabel("Time")
axes.set_ylabel("Temperature")
axes.legend()
axes.xaxis.grid()

# 强制X轴范围覆盖1996-2010(确保首尾年份刻度显示)
axes.set_xlim(pd.Timestamp("1996-01-01"), pd.Timestamp("2010-12-31"))

plt.tight_layout()  # 自动调整布局,防止标签被截断
plt.show()

关键修改说明

  1. 时间列转换:pd.to_datetime()将字符串时间转为datetime类型,是Matplotlib正确处理时间轴的核心前提。
  2. X轴刻度控制:mdates.YearLocator()强制每年生成一个刻度,DateFormatter("%Y")将刻度简化为年份格式。
  3. 代码优化:用groupby替代逐个站点切片,减少重复代码,后续新增站点只需调整标记列表即可。
  4. 布局优化:plt.xticks(rotation=45)和plt.tight_layout()解决X轴标签重叠问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:40:47