2

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?

yoonghm
  • 4,198
  • 1
  • 32
  • 48
Markus W
  • 1,451
  • 5
  • 19
  • 32
  • see related: http://stackoverflow.com/questions/34207409/formatting-of-datetimeindex-in-plot-pandas?rq=1 – EdChum Aug 22 '16 at 13:51
  • Thanks EdChum, I was hoping there would be a Parameter like ('%Y') to Format this in the df.plot() command. – Markus W Aug 22 '16 at 14:50

2 Answers2

4

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)
Markus W
  • 1,451
  • 5
  • 19
  • 32
1

I figured an alternative (better, at least to me) way is to add the following to df_Vol_new.plot() command:

plt.legend(df_Vol_new.index.to_period('A'))

This way you would reserve df_Vol_new.index datetime format while getting better plots at the same time.

atline
  • 28,355
  • 16
  • 77
  • 113
Lei Z
  • 11
  • 1