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

Matplotlib中X轴11月18日日期显示位置异常问题求助

问题原因及解决办法

核心问题

  1. 日期未被识别为日期类型:传给Matplotlib的X轴是字符串格式日期,Matplotlib会按字符串字典序排序,而非实际日期顺序。筛选11月数据后,原数据顺序混乱(加上reverse()反转进一步打乱),导致11-18的位置错误。
  2. 筛选逻辑存在漏洞:
    • 代码中day变量未正确赋值(应从badDestinations/goodDestinations中获取日期字段,比如badDestinations[j]["day"],当前代码未定义day,会导致筛选错误或报错)。
    • 用partition("-11-")筛选11月数据的方式不可靠,容易误判或因日期格式变化失效。
  3. 无意义的数据反转:若原数据并非按日期倒序存储,reverse()会直接打乱日期顺序。

分步解决

1. 修复数据筛选逻辑

确保正确获取日期字段,用更可靠的方式筛选11月数据:

# 初始化列表
Burns = []
Burnsday = []
target_month = "11"

# 处理badDestinations数据
for item in badDestinations:
    dest = item["destination"]
    wait_time = item["time"]
    day_str = item["day"]  # 确保数据中存在对应日期的字段
    # 拆分日期获取月份
    date_parts = day_str.split("-")
    if len(date_parts) == 3 and date_parts[1] == target_month:
        if dest == "Burns":
            Burns.append(wait_time)
            Burnsday.append(day_str)

# 处理goodDestinations数据
for item in goodDestinations:
    dest = item["destination"]
    wait_time = item["time"]
    day_str = item["day"]
    date_parts = day_str.split("-")
    if len(date_parts) == 3 and date_parts[1] == target_month:
        if dest == "Burns":
            Burns.append(wait_time)
            Burnsday.append(day_str)

2. 将字符串日期转换为可识别的日期类型

用datetime模块转换日期格式,并按日期排序:

from datetime import datetime

# 把字符串日期转为datetime对象
Burnsday_dt = [datetime.strptime(d, "%Y-%m-%d") for d in Burnsday]
# 按日期排序,确保数据时间顺序正确
sorted_data = sorted(zip(Burnsday_dt, Burns), key=lambda x: x[0])
sorted_dates, sorted_times = zip(*sorted_data)
# 转成列表(可选,zip返回元组)
sorted_dates = list(sorted_dates)
sorted_times = list(sorted_times)

3. 修正Matplotlib绘图代码

规范导入方式,确保参考线日期匹配格式:

import matplotlib.pyplot as plt

%matplotlib qt5

# 绘制Burns单元等待时间图表
plt.figure(1)
plt.title('Burns Unit Wait times')
plt.plot(sorted_dates, sorted_times)
# 设置参考线:先把参考日期转为datetime对象
ref_date = datetime.strptime("2022-11-18", "%Y-%m-%d")
plt.plot([ref_date, ref_date], [0, max(sorted_times)], 'r--')
plt.xlabel('Day')
plt.ylabel('Waiting time')
# 自动旋转X轴标签避免重叠
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

额外说明

之前跨月数据正常,是因为跨月字符串的字典序刚好和日期顺序一致(如2022-10-xx < 2022-11-xx < 2022-12-xx),但单月内数据顺序混乱时,字符串排序逻辑就会失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:50:24