TomSelleck
TomSelleck

Reputation: 6968

Plot hist with date index on x axis

I have the following data:

            num_incidents
date                     
2014-01-01            208
2014-01-02            112
...                   ...
2018-03-30             67
2018-03-31             77

If I try to plot it using the default histogram method, I get the following output:

daily_incidents_df.hist()
plt.show()

enter image description here

While this is useful, I'd also like to plot something like the following:

enter image description here

Upvotes: 0

Views: 713

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 31011

Assume that the source DataFrame contains:

            num_incidents
date                     
2014-01-01            208
2014-01-02            112
2015-02-02            100
2015-03-02            130
2016-02-02            130
2016-03-02            130
2011-02-02            170
2011-03-02            130
2018-03-30             67
2018-03-31             77

To compute yearly totals run:

s = df.num_incidents.groupby(df.index.year).sum()

Then to draw your picture, run:

ax = s.plot.bar(rot=0, width=0.9)
ax.set_xlabel('Year', fontsize=16)
ax.set_ylabel('Incidents', fontsize=16);

Note the ; terminating the last instruction, to suppress additional display concerning the last created drawing object.

Set width parmeter a little below 1.0, to fill almost all space with bars for each year. For the above data I got the following picture:

enter image description here

Upvotes: 2

Bruno Mello
Bruno Mello

Reputation: 4618

You can create a year column:

df['Year'] = df['date'].dt.year
df[['Year', 'num_incidents']].hist()

Upvotes: 1

Related Questions