Python 修改pandas条形图的图例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33149428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:52:09  来源:igfitidea点击:

Modify the legend of pandas bar plot

pythonpandasmatplotlibplot

提问by Benares

I am always bothered when I make a bar plot with pandas and I want to change the names of the labels in the legend. Consider for instance the output of this code:

当我用熊猫制作条形图时,我总是很烦恼,我想更改图例中标签的名称。例如,考虑此代码的输出:

import pandas as pd
from matplotlib.pyplot import *

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar')

enter image description hereNow, if I want to change the name in the legend, I would usually try to do:

在此处输入图片说明现在,如果我想更改图例中的名称,我通常会尝试这样做:

legend(['AAA', 'BBB'])

But I end up with this:

但我最终得到了这个:

enter image description here

在此处输入图片说明

In fact, the first dashed line seems to correspond to an additional patch.

事实上,第一条虚线似乎对应于一个额外的补丁。

So I wonder if there is a simple trick here to change the labels, or do I need to plot each of the columns independently with matplotlib and set the labels myself. Thanks.

所以我想知道这里是否有一个简单的技巧来更改标签,或者我是否需要使用 matplotlib 独立绘制每一列并自己设置标签。谢谢。

采纳答案by Sergey Bushmanov

Changing labels for Pandas df.plot():

更改 Pandas 的标签df.plot()

import pandas as pd
from matplotlib.pyplot import *

fig, ax = subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
ax.legend(["AAA", "BBB"]);

enter image description here

在此处输入图片说明

Edit:

编辑:

One line less:

少一行:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.legend(["AAA", "BBB"]);

enter image description here

在此处输入图片说明

回答by Jonathan

If you need to call plot multiply times, you can also use the "label" argument:

如果您需要调用 plot 乘法次数,您还可以使用“label”参数:

ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')

While this is not the case in the OP question, this can be helpful if the DataFrameis in long format and you use groupbybefore plotting.

虽然在 OP 问题中不是这种情况,但如果它DataFrame是长格式并且您groupby在绘图之前使用,这可能会有所帮助。

回答by gibbone

This is slightly an edge case but I think it can add some value to the other answers.

这有点边缘情况,但我认为它可以为其他答案增加一些价值。

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

如果您向图形添加更多细节(例如注释或线条),您很快就会发现当您在轴上调用图例时它是相关的:如果您在脚本底部调用它,它将捕获不同的句柄传奇元素,搞砸了一切。

For instance the following script:

例如下面的脚本:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

会给你这个数字,这是错误的: 在此处输入图片说明

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after severaloperations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

虽然这是一个玩具示例,可以通过更改命令的顺序轻松修复,但有时您需要在多次操作后修改图例,因此下一个方法将为您提供更大的灵活性。例如,这里我还更改了图例的字体大小和位置:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

这是你会得到的:

enter image description here

在此处输入图片说明