猿问

在直方图 matplotlib 的 x 轴上将月份数字切换为月份名称

我有一个超过一年的数据点的直方图。一切正常,除了月份显示为数字。我想用他们的名字显示它们。而不是“01”,它应该说“一月”(也稍微旋转,但我自己可以这样做。)我如何告诉 maplotlib 使用月份名称?


我已经查看了文档和其他帖子,但无法使其工作。


我的代码:


fig = plt.figure(figsize=(12,6))

s = fig.add_subplot(111)

s.hist(mydata,bins=120,stacked=True, color=mycolors, alpha=1)

s.xaxis.set_major_locator(mdates.MonthLocator())

s.xaxis.set_major_formatter(mdates.DateFormatter('%m'))

s.legend(legend)

作为mydata形状 (n,1) 的数据帧列表。我是 matplotlib 的新手,不完全理解发生了什么,s.xaxis.set_major_formatter(mdates.DateFormatter('%m'))但我猜这条线需要修改吗?


我的代码结果如下图:

德玛西亚99
浏览 202回答 2
2回答

一只名叫tom的猫

在 DateFormatter 中使用 %B 来获取月份名称,而不是 %m 给出的月份编号。您还可以使用 %b 来获取缩写名称。

当年话下

只需要替换 mdates.DateFormatter 中的月份格式:#fig = plt.figure(figsize=(12,6))#s = fig.add_subplot(111)#s.hist(mydata,bins=120,stacked=True, color=mycolors, alpha=1)#s.xaxis.set_major_locator(mdates.MonthLocator())s.xaxis.set_major_formatter(mdates.DateFormatter('%b'))ORs.xaxis.set_major_formatter(mdates.DateFormatter('%B'))#s.legend(legend)B = 长名称 b = 缩写名称
随时随地看视频慕课网APP

相关分类

Python
我要回答