Suppose I have a Series like this.
In[10]: month_series
Out[10]:
2016-01-01 4880
2016-02-01 4579
2016-03-01 6726
2016-04-01 1778
2016-05-01 3303
2016-06-01 5402
2016-07-01 1207
2016-08-01 6176
2016-09-01 5586
2016-10-01 2802
2016-11-01 6944
2016-12-01 3580
2017-01-01 9336
dtype: int64
I want to just construct a bar plot to compare month to month, which seems quite simple with
In[11]: month_series.plot(kind='bar')
Out[11]:
I really don't need anything much more than that, but my issue is that the dates look terrible on the x-axis - I subsequently wanted to format the dates so that I just provide the year and month, some format like %Y-%m
. How can I do so?
My struggles
So, looking at the documentation for pandas.Series.plot
I see the xticks
argument that can be passed, and figure I can use strftime
to format the dates and pass as a sequence.. but this doesn't work because the ticks require numerical values or dates, not strings.
So then I figure I should just use raw matplotlib instead, so that I can use set_major_formatter
with a DateFormatter
to modify the tick labels. But if I just use plt.bar
, that introduces a new issue - the entire date range is used, which makes sense.
In[17]: plt.bar(month_sereis.index, month_sereis.values)
Out[17]: <Container object of 13 artists>
At this point I'm quite convinced I'm missing something and there's a trivially simple way to do this.
You can make use of matplotlib.axes.Axes.set_xticklabels
whose argument labels
accepts a string like sequence (anything printable with "%s"
conversion) and then make use of DateTimeIndex.strftime
to specify the format you'd want the labels to appear in.
ax = month_series.plot.bar()
# ax.set_xticklabels(month_series.index.to_period('M')) also works
ax.set_xticklabels(month_series.index.strftime('%Y-%m'))
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With