Formatting Date Stamps in a Bar Chart

My question

Suppose I have such a series.

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 build a bar chart to compare month after month, which seems pretty simple with

In[11]: month_series.plot(kind='bar')
Out[11]: 

enter image description here

I really don’t need anything much more, but my problem is that the dates look horrible on the x axis - I later wanted to format the dates so that I simply provided the year and month in some format %Y-%m. How to do it ?


My struggle

So, looking at the documentation for pandas.Series.plotI see an argument xticksthat can be passed, and a number that I can use strftimeto format dates and transfer as a sequence .. but this does not work because ticks require numeric values ​​or dates, not strings.

, , raw matplotlib, set_major_formatter DateFormatter . plt.bar, - , .

In[17]: plt.bar(month_sereis.index, month_sereis.values)
Out[17]: <Container object of 13 artists>  

enter image description here

, - , .

+4
1

matplotlib.axes.Axes.set_xticklabels, labels , (, "%s"), DateTimeIndex.strftime, , .

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()

enter image description here

+4

Source: https://habr.com/ru/post/1666744/


All Articles