Mike J Mike J - 24 days ago 12
Python Question

Axis interval spacing when plotting with pandas timedelta

I'm trying to plot some columns in a dataframe that has pandas timedelta values as its index. When I plot it, all the points are evenly spaced along the x axis even if there's a variable time between.

time = [pd.Timestamp('9/3/2016')-pd.Timestamp('9/1/2016'),pd.Timestamp('9/8/2016')-pd.Timestamp('9/1/2016'),pd.Timestam\p('9/29/2016')-pd.Timestamp('9/1/2016')]
df = pd.DataFrame(index=time, columns=['y'],data=[5,0,10])
df.plot()
plt.show()


Wrong spacing

If instead I used dates instead of timedelta, I get the proper spacing on the x axis:

time = [pd.Timestamp('9/3/2016'),pd.Timestamp('9/5/2016'),pd.Timestamp('9/20/2016')]
df = pd.DataFrame(index=time, columns=['y'],data=[5,0,10])
df.plot()
plt.show()


Right spacing

Is there a way to get this to display correctly?

Answer

At the moment, it's not fully supported yet in pandas. Please see this issue on Github for more info.

For a quick workaround, you can use:

import matplotlib.pyplot as plt
plt.plot(df.index, df.values)

Here's an example of how you could play with the ticks to make them readable (rather than just a very large number)

import matplotlib as mpl
import datetime
fig, ax = plt.subplots()
ax.plot(df.index, df.values)
plt.xticks([t.value for t in df.index], df.index, rotation=45)
plt.show()

result