John Smith
John Smith

Reputation: 281

Changing xticks in a pandas plot

I am trying to graph the number of active users by hour in a histogram.

Here is my code:

import pandas as pd
import datetime
from matplotlib import pyplot as plt

data =  [datetime.datetime(2000, 1, 1, 11, 5, 44, 233144), datetime.datetime(2000, 1, 1, 12, 5, 45, 175807), ..]

df = pd.DataFrame(data,  columns=['Users'])
df.index = pd.to_datetime(df['Users'])
df.groupby(pd.TimeGrouper(freq='60Min')).count().plot(kind='bar', title = 'Activity by Hour', figsize = (10,8))

plt.xlabel('Time')
plt.ylabel('Number of Users')
plt.show()

This works great, but I originally was given only time of day data, not date (I added in the 1/1/2000 to every entry because everything I found about plotting this used datetimes and datetime.time format wasn't working; i.e can't convert to the right format using pf.to_datetime() unless you have a datetime).

Now all of the xtick labels are 2000_01_01 00:00:00, 2000_01_01 01:00:00, etc.

I want to change them to just be the time (i.e. get them and then chop off the first part of the string), but I can't figure out how to do this.

Upvotes: 0

Views: 2037

Answers (1)

iDrwish
iDrwish

Reputation: 3103

I believe you should use the add_subplot() command, it gives you more control over figures and limit the plt API commands to the intent figure.

I added a few lines on using subplots and changing the xticklabels.

import pandas as pd
import datetime
from matplotlib import pyplot as plt

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

data =  [datetime.datetime(2000, 1, 1, 11, 5, 44, 233144), datetime.datetime(2000, 1, 1, 12, 5, 45, 175807)]
df = pd.DataFrame(data,  columns=['Users'])
df.index = pd.to_datetime(df['Users'])

plotting_data = df.groupby(pd.TimeGrouper(freq='60Min')).count()
plotting_data.plot(ax=ax, kind='bar')

ax.set_title('Activity by Hour')
ax.set_xlabel('Time')
ax.set_ylabel('Number of Users')
ax.set_xticklabels(list(plotting_data.index.time))

I prefer to use the subplot instance methods myself in the interest of being explicit and especially when working with multiple subplots.

Upvotes: 1

Related Questions