2017-06-22 92 views
2

我想绘制一个索引是无常DatatimeIndex的熊猫系列。我的代码如下:如何删除多余的日期时间,当X轴是不间断的熊猫日期时间索引

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() 

输出为:enter image description here 但结果是不是我真正想要的,因为2000-01-01 00:04:00也是在图像上绘制。期望的结果是,在x轴03:00是07:00旁边,图像应该是一条直线。希望你有个好主意。

回答

2

一个可能的解决方案是通过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() 

graph

+0

在我的项目中,我使用'LineCollection'绘制多色线。你可以看看我以前的问题。 https://stackoverflow.com/questions/44642966/how-to-plot-multi-color-line-if-x-axis-is-date-time-index-of-pandas'LineCollection'要求坐标能够'浮动'。虽然这种方法非常好,但它不能用在我的项目中。不管怎样,谢谢你。 –

+0

@Jeng我觉得这个答案直接适用于你的问题。你有没有试过使用它?问题是什么? – ImportanceOfBeingErnest

+0

对不起,我的粗心大意,这种方法真的适用于我的项目。但是xticks太密集了。我想显示“年份”而不是“分钟”,但是我发现设置定位符和格式化程序没有帮助。你有什么好主意吗?非常感谢您的好意。 –