Search code examples
pandasmatplotlibplotgroup-byticker

Pandas df histo, format my x ticker and include empty


I got this pandas df:

index      TIME
12:07      2019-06-03  12:07:28
10:04      2019-06-04  10:04:25
11:14      2019-06-09  11:14:25
...

I use this command to do an histogram to plot how much occurence for each 15min periods

df['TIME'].groupby([df["TIME"].dt.hour, df["TIME"].dt.minute]).count().plot(kind="bar")

my plot look like this:

enter image description here

How can I get x tick like 10:15 in lieu of (10, 15) and how manage to add x tick missing like 9:15, 9:30... to get a complet time line??


Solution

  • You can resample your TIME column to 15 mins intervalls and count the number of rows. Then plot a regular bar chart.

    df = pd.DataFrame({'TIME': pd.to_datetime('2019-01-01') + pd.to_timedelta(pd.np.random.rand(100) * 3, unit='h')})
    df = df[df.TIME.dt.minute > 15] # make gap
    
    ax = df.resample('15T', on='TIME').count().plot.bar(rot=0)
    ticklabels = [x.get_text()[-8:-3] for x in ax.get_xticklabels()]
    ax.xaxis.set_major_formatter(matplotlib.ticker.FixedFormatter(ticklabels))
    

    (for details about formatting datetime ticklabels of pandas bar plots see this SO question)

    enter image description here