Eri*_*sen 8 python plot matplotlib python-2.7 pandas
假设我有一个这样的系列。
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
Run Code Online (Sandbox Code Playgroud)
我只想构建一个条形图来比较月与月,这看起来很简单
In[11]: month_series.plot(kind='bar')
Out[11]:
Run Code Online (Sandbox Code Playgroud)
我真的不需要比这更多的东西了,但我的问题是日期在 x 轴上看起来很糟糕 - 我随后想格式化日期,以便我只提供年份和月份,例如%Y-%m. 我怎么能这样做?
我的挣扎
因此,查看文档,pandas.Series.plot我看到了xticks可以传递的参数,并且图我可以strftime用来格式化日期并作为序列传递.. 但这不起作用,因为刻度需要数值或日期,而不是字符串。
所以我想我应该只使用原始 matplotlib,这样我就可以使用set_major_formatteraDateFormatter来修改刻度标签。但是,如果我只使用plt.bar,则会引入一个新问题 - 使用整个日期范围,这是有道理的。
In[17]: plt.bar(month_sereis.index, month_sereis.values)
Out[17]: <Container object of 13 artists>
Run Code Online (Sandbox Code Playgroud)
在这一点上,我非常确信我遗漏了一些东西,并且有一种非常简单的方法可以做到这一点。
您可以使用matplotlib.axes.Axes.set_xticklabelswho 参数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()
Run Code Online (Sandbox Code Playgroud)