Skip to main content
 首页 » 编程设计

python之x轴不连续时如何删除冗余日期时间pandas DatetimeIndex

2024年10月01日8jiqing9006

我想绘制一个 pandas 系列,其索引是不计其数的 DatatimeIndex。我的代码如下:

import matplotlib.dates as mdates 
index = pd.DatetimeIndex(['2000-01-01 00:00:00', '2000-01-01 00:01:00', 
           '2000-01-01 00:02:00', '2000-01-01 00:03:00', 
           '2000-01-01 00:07:00', 
           '2000-01-01 00:08:00'], 
          dtype='datetime64[ns]') 
df = pd.Series(range(6), index=index) 
print(df) 
plt.plot(df.index, df.values) 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%M")) 
plt.show() 

输出是: 但结果并不是我真正想要的,因为 2000-01-01 00:04:00 也绘制在图像上。期望的结果是在 x 轴上 03:00 紧挨着 07:00,图像应该是一条直线。期待你的好主意。

请您参考如下方法:

一个可能的解决方案是通过 strftime 将索引转换为 string并使用 Series.plot :

s = pd.Series(range(6), index=index) 
print(s) 
2000-01-01 00:00:00    0 
2000-01-01 00:01:00    1 
2000-01-01 00:02:00    2 
2000-01-01 00:03:00    3 
2000-01-01 00:07:00    4 
2000-01-01 00:08:00    5 
dtype: int32 
 
s.index = s.index.strftime('%M') 
s.plot() 

另一种解决方案是通过arange 绘制然后添加xticks :

x = np.arange(len(s.index)) 
plt.plot(x, s) 
plt.xticks(x, s.index.strftime('%M')) 
plt.show()