简体   繁体   English

如何更改 Groupby 生成的 plot 中的 x 轴标签

[英]How to change x-axis labels in plot generated by Groupby

I want to replace the current x-axis label to the label shown below:我想把当前x轴的label替换成下图的label:
labels = ["Oct","Nov","Dec", "Jan", "Feb", "Mar", "April", "May", "June", "July"] labels = ["十月","十一月","十二月", "一月", "二月", "三月", "四月", "五月", "六月", "七月"]

The code I've used to generate the plot is:我用来生成 plot 的代码是:

df.groupby(pd.Grouper(key='Date', freq='1M')).sum().plot.bar(legend=False)

The output that I got is shown below, here you can see the x-axis have label as dates.我得到的 output 如下所示,在这里你可以看到 x 轴有 label 作为日期。

在此处输入图像描述

How I can replace those labels with Month names?我如何用月份名称替换这些标签?

First generate your groupby result:首先生成您的groupby结果:

tbl = df.groupby(pd.Grouper(key='Date', freq='M')).sum()

Then change the index from "full" dates into abbreviated month names:然后将索引从“完整”日期更改为缩写月份名称:

tbl.set_index(tbl.index.month_name().rename('Month').map(lambda tt: tt[:3]), inplace=True)

And finally draw your figure:最后画出你的身材:

tbl.plot.bar(legend=False);

Note the trailing ;注意尾随; to prevent from additional display concerning the type of the created object.以防止额外显示有关创建的 object 的类型。

You could have a look atDate formatters .你可以看看Date formatters There exists DateFormatter class which accepts a fmt argument which is a strftime format string.存在DateFormatter class,它接受一个fmt参数,它是一个strftime格式字符串。

Here is a reference of strftime() and strptime() format codes. strftime()strptime()格式代码的参考。

To format as month abbreviated name, you need to use %b .要格式化为月份缩写名称,您需要使用%b

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

ax = df.groupby(pd.Grouper(key='Date', freq='1M')).sum().plot.bar(legend=False)

ax.xaxis.set_major_formatter(mdates.DateFormatter(fmt='%b'))

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM