Python x轴不连续时如何删除冗余的日期时间

Python x轴不连续时如何删除冗余的日期时间,python,pandas,matplotlib,series,Python,Pandas,Matplotlib,Series,我想画一个熊猫系列,它的索引是不连续的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', '

我想画一个熊猫系列,它的索引是不连续的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相邻,图像应为直线。希望您有好主意。

一种可能的解决方案是将索引转换为
字符串,并使用:

另一种解决方案是按
arange
绘图,然后添加:



在我的项目中,我使用
LineCollection
绘制一条多色线。你可以看看我的前一个问题<代码>行集合
要求坐标能够为“浮动”。虽然这种方法很好,但不能用在我的项目中。无论如何谢谢你。@JZeng我认为这个答案直接适用于你的问题。你试过用它吗?问题是什么?对不起我的粗心,这个方法对我的项目很有效。但是xticks太密集了。我想显示“年”而不是“分钟”,但我发现设置定位器和格式化程序没有帮助。你有什么好主意吗?非常感谢您的好意。
plt.xticks(x,s.index.strftime(“%Y”)
不起作用?可能需要更改。例如,2012年的分钟数太多,如果我使用
plt.xticks(x,s.index.strftime(%Y))
,在x轴上有太多的2012年,每分钟一个2012年,但我只希望一年的数据有一个2012年。
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()
x = np.arange(len(s.index))
plt.plot(x, s)
plt.xticks(x, s.index.strftime('%M'))
plt.show()