Search code examples
pythonpandasmatplotlibformattingdatetimeindex

Pandas plotting: How to format datetimeindex?


I am doing a barplot out of a dataframe with a 15min datetimeindex over a couple of years. Using this code:

df_Vol.resample(
    'A',how='sum'
).plot.bar(
    title='Sums per year',
    style='ggplot',
    alpha=0.8
)

Unfortunately the ticks on the X-axis are now shown with the full timestamp like this: 2009-12-31 00:00:00.

I would prefer to Keep the code for plotting short, but I couldn't find an easy way to format the timestamp simply to the year (2009...2016) for the plot.

Can someone help on this?


Solution

  • As it does not seem to be possible to Format the date within the Pandas df.plot(), I have decided to create a new dataframe and plot from it.

    The solution below worked for me:

    df_Vol_new = df_Vol.resample('A',how='sum')
    df_Vol_new.index = df_Vol_new.index.format(formatter=lambda x: x.strftime('%Y')) 
    ax2 =df_Vol_new.plot.bar(title='Sums per year',stacked=True, style='ggplot', alpha=0.8)