x轴不连续的 pandas 时如何删除多余的日期时间DatetimeIndex [英] how to remove redundant date time when x-axis is incontinuous pandas DatetimeIndex
问题描述
我想绘制一个熊猫系列,其索引是不连续的DatatimeIndex.我的代码如下:
I want to plot a pandas series which index is incountinuous DatatimeIndex. My code is as follows:
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,并且图像应该是一条直线.希望你的好主意.
The output is: But the result is not what I really want, because 2000-01-01 00:04:00 is also plotted on the image. The desired outcome is that on the x-axis 03:00 is next to 07:00 and the image should be a straight line. Hope for your great idea.
推荐答案
一种可能的解决方案是通过strftime
并使用
One possible solution is convert index to string
by strftime
and use 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
:
Another solution is plot by arange
and then add xticks
:
x = np.arange(len(s.index))
plt.plot(x, s)
plt.xticks(x, s.index.strftime('%M'))
plt.show()
这篇关于x轴不连续的 pandas 时如何删除多余的日期时间DatetimeIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!