Matplotlib绘制月度时间序列时如何显示全部完整日期?
问题解决:Matplotlib x轴完整显示7月日期并设置指定格式
核心问题原因
多次调用df.plot()时,Pandas会自动重新处理x轴的刻度与格式,覆盖你手动设置的DateFormatter和DayLocator,导致配置不生效。
方案一:统一绘制后强制重置轴属性
在所有周度数据绘制完成后,重新设置x轴规则,并强制锁定x轴范围覆盖整个7月:
import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd fig, ax = plt.subplots(figsize=(25, 10)) # 绘制所有周度数据 df_0.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 1') df_1.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 2') df_2.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 3') df_3.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 4') df_4.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 5') # 设置轴标签 plt.xlabel('Date and Time of the month - July') plt.ylabel('Temperature') # 强制设置x轴为每日一个刻度 ax.xaxis.set_major_locator(mdates.DayLocator(interval=1)) # 设置日期格式为「日-月-年」(对应你要的22-07-2022格式) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) # 锁定x轴范围为整个7月的日期区间 all_dates = pd.concat([df_0['Date and Time'], df_1['Date and Time'], df_2['Date and Time'], df_3['Date and Time'], df_4['Date and Time']]) ax.set_xlim(all_dates.min(), all_dates.max()) # 自动旋转日期标签避免重叠 plt.gcf().autofmt_xdate() plt.show()
方案二:改用Matplotlib原生绘图方法
跳过Pandas的plot方法,直接使用Matplotlib原生接口绘制,对轴的控制更直接:
import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd fig, ax = plt.subplots(figsize=(25, 10)) # 用Matplotlib原生方法绘制各周数据 ax.plot(df_0['Date and Time'], df_0['Temperature'], label='Week 1') ax.plot(df_1['Date and Time'], df_1['Temperature'], label='Week 2') ax.plot(df_2['Date and Time'], df_2['Temperature'], label='Week 3') ax.plot(df_3['Date and Time'], df_3['Temperature'], label='Week 4') ax.plot(df_4['Date and Time'], df_4['Temperature'], label='Week 5') # 设置轴标签 ax.set_xlabel('Date and Time of the month - July') ax.set_ylabel('Temperature') # 设置x轴刻度与格式 ax.xaxis.set_major_locator(mdates.DayLocator(interval=1)) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) # 锁定x轴范围 all_dates = pd.concat([df_0['Date and Time'], df_1['Date and Time'], df_2['Date and Time'], df_3['Date and Time'], df_4['Date and Time']]) ax.set_xlim(all_dates.min(), all_dates.max()) # 自动旋转日期标签 plt.gcf().autofmt_xdate() # 添加图例 ax.legend() plt.show()
额外说明
- 若需要其他日期格式,可修改
DateFormatter的格式码:比如%m-%d-%Y对应07-22-2022(月-日-年)。 - 设置
xlim是为了避免Matplotlib自动截断x轴范围,确保7月所有日期都能显示。
内容的提问来源于stack exchange,提问作者umar
相关产品推荐
相关产品推荐

