我的问题
假设我有一个这样的系列。
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
我只想构建一个条形图来比较每月,这看起来很简单
In[11]: month_series.plot(kind='bar')
Out[11]:
我真的不需要更多的东西,但我的问题是日期在 x 轴上看起来很糟糕 - 我随后想格式化日期,以便我只提供年份和月份,某种格式,例如%Y-%m
. 我怎样才能这样做?
我的挣扎
因此,查看文档pandas.Series.plot http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html我看到xticks
可以传递的参数,并且我可以使用strftime
格式化日期并作为序列传递..但这不起作用,因为刻度需要数值或日期,而不是字符串。
所以我想我应该使用原始 matplotlib 来代替,这样我就可以使用set_major_formatter http://matplotlib.org/api/ticker_api.html#tick-formatting with a DateFormatter
修改刻度标签。但如果我只是使用plt.bar
,这引入了一个新问题 - 使用整个日期范围,这是有道理的。
In[17]: plt.bar(month_sereis.index, month_sereis.values)
Out[17]: <Container object of 13 artists>
在这一点上,我非常确信我错过了一些东西,并且有一个非常简单的方法可以做到这一点。
您可以利用matplotlib.axes.Axes.set_xticklabels
谁的论点labels
接受类似序列的字符串(任何可打印的内容"%s"
转换),然后利用DateTimeIndex.strftime http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.strftime.html指定您希望标签显示的格式。
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)