Pandas仅取2个日期索引数据绘图时x轴出现大量乱码数字如何解决
Pandas 少样本时间序列绘图日期显示异常解决方案
问题复现
现有已设置日期索引的DataFrame如下:
import pandas as pd df = pd.DataFrame({'a':[20,30,12],'b':[15,18,18]}, index=['2021-10-7','2021-10-8','2021-10-9']) df.index = pd.to_datetime(df.index)
执行df.iloc[-2:].plot()绘制最后2条数据时,x轴显示为无意义的长数字,而执行df.plot()绘制全量3条数据时日期显示完全正常。
问题原因
当时间序列样本量≤2时,pandas绘图的默认逻辑不会将索引识别为待格式化的时间刻度,而是直接转换为int类型的时间戳数值展示,因此会出现异常的长数字。全量样本有3个数据点,触发了默认的时间轴格式化规则,因此显示正常。
解决方法
以下三种方案均可解决该问题:
- 方案1:传递
x_compat=True参数强制启用时间兼容模式,最简原生方案
df.iloc[-2:].plot(x_compat=True)
- 方案2:手动格式化matplotlib的x轴刻度,灵活度最高
import matplotlib.pyplot as plt import matplotlib.dates as mdates sub_df = df.iloc[-2:] ax = sub_df.plot() # 自定义x轴日期展示格式 ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # 可选:设置刻度间隔为1天,避免生成多余空刻度 ax.xaxis.set_major_locator(mdates.DayLocator(interval=1)) plt.show()
- 方案3:将索引转为字符串类型强制按文本展示,无需额外依赖
sub_df = df.iloc[-2:] sub_df.index = sub_df.index.strftime('%Y-%m-%d') sub_df.plot()
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

