如何设置Matplotlib折线图的Datetime索引X轴刻度:显示完整日期或仅小时
解决方案
一、让X轴显示完整日期
Matplotlib默认会截断过长的日期字符串,你可以通过指定日期格式化器来强制显示完整的datetime信息,同时配合自动刻度定位器避免刻度重叠:
import matplotlib.dates as mdates fig, ax = plt.subplots(figsize=(15, 7)) fig.suptitle('Error 1') ax.set_xlabel('Hour') plt.xticks(rotation=45) ax.set_ylabel('Error', rotation=0) ax.grid(alpha=0.25) legs = day_1.columns[:] # 设置X轴刻度为完整日期格式 ax.xaxis.set_major_locator(mdates.AutoDateLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S%z')) for column in day_1: ax.plot(day_1.index, day_1[column]) ax.legend(legs, loc='upper right') fig.tight_layout() plt.show()
AutoDateLocator会根据数据范围自动调整刻度间隔,防止刻度过于密集重叠DateFormatter('%Y-%m-%d %H:%M:%S%z')指定了包含时区的完整日期时间显示格式
二、让X轴只显示小时
你之前的错误在于使用了错误的方法名(set_xtick应为set_xticks),且未将小时标签与原索引位置对应,导致X轴空白。以下两种方法可以解决:
方法1:手动替换刻度标签(适合数据量较小的场景)
fig, ax = plt.subplots(figsize=(15, 7)) fig.suptitle('Error 1') ax.set_xlabel('Hour') plt.xticks(rotation=45) ax.set_ylabel('Error', rotation=0) ax.grid(alpha=0.25) legs = day_1.columns[:] # 保留原索引的刻度位置,将标签替换为小时值 ax.set_xticks(day_1.index) ax.set_xticklabels([dt.hour for dt in day_1.index]) for column in day_1: ax.plot(day_1.index, day_1[column]) ax.legend(legs, loc='upper right') fig.tight_layout() plt.show()
方法2:用日期格式化器提取小时(更灵活)
import matplotlib.dates as mdates fig, ax = plt.subplots(figsize=(15, 7)) fig.suptitle('Error 1') ax.set_xlabel('Hour') plt.xticks(rotation=45) ax.set_ylabel('Error', rotation=0) ax.grid(alpha=0.25) legs = day_1.columns[:] # 通过格式化器直接只显示小时部分 ax.xaxis.set_major_locator(mdates.AutoDateLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H')) for column in day_1: ax.plot(day_1.index, day_1[column]) ax.legend(legs, loc='upper right') fig.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

