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

Matplotlib如何设置指定起始日期的X轴日期标签?

解决Matplotlib绘制2022年2月体重折线图X轴日期标签不符问题

问题核心

当前X轴标签内容不符、xlim设置无效,本质是X轴数据未正确转换为datetime类型,且直接用字符串设置xlim无法被Matplotlib识别。

修复代码

以下是调整后的完整代码,确保X轴显示你指定的['2/4', '2/27']范围内的日期标签:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

# FEB
# 配置画布和绘图空间
fig, lx = plt.subplots(figsize=(30,10))

# 1. 处理X轴日期:将目标日期列表转换为datetime对象
target_dates = ['2/4', '2/5', '2/6', '2/7', '2/8', '2/9', '2/10', '2/11', 
                '2/12', '2/13', '2/14', '2/15', '2/16', '2/17', '2/18', 
                '2/19', '2/20', '2/21', '2/22', '2/23', '2/24', '2/25', 
                '2/26', '2/27']
# 转换为2022年的datetime对象
x_dates = [datetime.strptime(f'2022-{d}', '%Y-%m/%d') for d in target_dates]

# 2. 处理体重数据(确保和日期列表长度匹配)
wd = df2['Unnamed: 1'].astype(float)
# 只取对应日期范围的数据(如果df2的长度和target_dates一致可跳过此步)
wd = wd[:len(x_dates)]

# 3. 绘制折线图,使用datetime类型的X轴数据
lx.plot(x_dates, wd)

# 设置轴标签和标题
lx.set(xlabel='Day', ylabel='Weight', title='Daily Weight February 2022')

# 4. 配置X轴日期显示格式和刻度
date_format = mdates.DateFormatter('%m/%d')
lx.xaxis.set_major_formatter(date_format)
# 设置主刻度为你指定的所有日期
lx.set_xticks(x_dates)
# 设置X轴范围为目标起始和结束日期
lx.set_xlim(x_dates[0], x_dates[-1])

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

plt.show()

关键修复点

  • 强制转换X轴为datetime类型:Matplotlib对日期的处理依赖datetime对象,字符串无法被正确解析为日期刻度。
  • 直接指定xticks:用你需要显示的日期列表设置X轴刻度,确保标签完全匹配。
  • 正确设置xlim:使用datetime对象而非字符串定义X轴范围,确保生效。
  • 添加标签旋转:避免日期标签重叠,提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:05:20