urschrei
urschrei

Reputation: 26859

Matplotlib plotting x ticks from Pandas DataFrame incorrectly

I have a Pandas DataFrame containing 20 rows, indexed by datetime:

df.tail()
                     units       value
time        
2013-08-30T13:01:12  vehicles/h  662
2013-08-30T13:06:12  vehicles/h  701
2013-08-30T13:11:13  vehicles/h  477
2013-08-30T13:16:13  vehicles/h  179
2013-08-30T13:21:13  vehicles/h  576

I'm plotting it using matplotlib, like so:

ax = ls.plot(color='CC00CC')
# Only show hours and minutes
ax.set_xticklabels(
    [dt.strftime("%H:%M:%S") for dt in ls.index.to_datetime()])
plt.setp(ax.get_yticklabels(), fontsize=8)
ax.set_ylabel("Counts")
ax.set_xlabel("5-minute intervals on %s" % (datetime.datetime.today().strftime("%d/%m/%Y")))
plt.title("Vehicles")
plt.tight_layout()

Which results in the following plot:

enter image description here

But only the first few times are being shown as x ticks. The right-most x tick should be labelled 12:21:13, and some more of the intermediate ticks should be shown. What have I done wrong?

Upvotes: 1

Views: 1523

Answers (1)

urschrei
urschrei

Reputation: 26859

Turns out that I wasn't actually converting the time column to a DateTimeIndex properly. Doing that correctly fixed it:

Here's what my time column looked like:

df['time'][0]
>> u'2014-03-04T19:01:11'

Conversion like so:

# convert to DateTimeIndex, convert to UTC, and sort
df['time'] = pd.to_datetime(df['time'], format="%Y-%m-%dT%H:%M:%S")
df = df.set_index('time').tz_convert('UTC').sort()

Upvotes: 2

Related Questions