how to remove redundant date time when x-axis is incontinuous pandas DatetimeIndex

两盒软妹~` 提交于 2020-01-14 01:06:10

问题


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

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.


回答1:


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

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



来源:https://stackoverflow.com/questions/44690454/how-to-remove-redundant-date-time-when-x-axis-is-incontinuous-pandas-datetimeind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!