How to remove redundant date time when x axis is incontinence pandas DatetimeIndex

I want to build a pandas series whose index has no DatatimeIndex value. My code looks like this:

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

      

Conclusion: enter image description here But the result is not what I really want, because 2000-01-01 00:04:00 is also plotted on the image. The desired result is that on the x-axis 03:00 is near 07:00 and the image should be straight. Hope for your great idea.

+2


source to share


1 answer


One possible solution is to convert the index to string

with 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 a graph arange

and then add xticks

:



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

      


graph

+2


source







All Articles