在条形图上格式化日期标签 [英] Formatting date labels on bar plot
问题描述
我的问题
假设我有一个这样的系列.
在[10]:month_series出[10]:2016-01-01 48802016-02-01 45792016-03-01 67262016-04-01 17782016-05-01 33032016-06-01 54022016-07-01 12072016-08-01 61762016-09-01 55862016-10-01 28022016-11-01 69442016-12-01 35802017-01-01 9336dtype:int64
我只想构建一个条形图来比较月与月,这对于
来说似乎很简单 在[11]中:month_series.plot(kind ='bar')出[11]:
我真的不需要更多,但是我的问题是日期在x轴上看起来很糟糕-我后来想格式化日期,以便只提供年份和月份,例如%Y-%m
.我该怎么做?
我的挣扎
因此,查看
此时我非常确信我遗漏了一些东西,并且有一种非常简单的方法可以做到这一点.
您可以使用 matplotlib.axes.Axes.set_xticklabels
其参数 labels
接受一个字符串,如序列(任何可通过 "%s"
转换打印的内容),然后使用
My question
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()
这篇关于在条形图上格式化日期标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!