如何修复Python Plot中日期时间X轴偏移问题?
解决X轴日期偏移问题
核心问题大概率是日期列未转为datetime类型,或者Matplotlib默认的X轴刻度没有对齐到月末,导致视觉上的偏移。以下是具体解决步骤:
1. 确保日期列是datetime格式
如果你的Date列是字符串类型,Matplotlib无法正确解析日期逻辑,会导致刻度偏移。先转换为datetime类型:
import pandas as pd # 转换test和previsao的Date列为datetime test['Date'] = pd.to_datetime(test['Date']) previsao['Date'] = pd.to_datetime(previsao['Date'])
2. 手动设置X轴刻度对齐到月末
Matplotlib默认的日期刻度不会自动对齐到月末,需要用MonthLocator指定定位到每月最后一天,并设置日期格式化方式:
import matplotlib.pyplot as plt import matplotlib.dates as mdates fig = plt.figure(figsize=(12, 8)) plt.plot(test.Date, test.Precipitation, 's-r') plt.plot(previsao.Date, previsao.Precipitation, 's-b') plt.title('Precipitação por Mês na Cidade de São Paulo em $mm$', fontsize=20) plt.ylabel('Precipitação ($mm$)', fontsize=12) plt.xlabel('Ano') plt.legend(['Real', 'Previsão']) # 设置X轴刻度为每月最后一天 locator = mdates.MonthLocator(bymonthday=-1) # 格式化日期显示为「年-月」 formatter = mdates.DateFormatter('%Y-%m') plt.gca().xaxis.set_major_locator(locator) plt.gca().xaxis.set_major_formatter(formatter) # 旋转X轴标签避免重叠 plt.xticks(rotation=45) # 调整布局防止标签被截断 plt.tight_layout() plt.show()
额外验证步骤
如果调整后仍有问题,检查日期列是否确实为月末日期:
# 验证test的Date列是否都是月末 print(test['Date'].dt.is_month_end) # 验证previsao的Date列是否都是月末 print(previsao['Date'].dt.is_month_end)
如果输出有False,说明你的数据日期本身不是月末,需要先修正数据中的日期值。
内容的提问来源于stack exchange,提问作者Matheus Alves
相关产品推荐
相关产品推荐

