修改pandas条形图的图例 [英] Modify the legend of pandas bar plot

查看:32
本文介绍了修改pandas条形图的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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')

现在,如果我想更改图例中的名称,我通常会尝试这样做:

Now, if I want to change the name in the legend, I would usually try to do:

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

但我最终得到了这个:

实际上,第一条虚线似乎对应一个附加补丁.

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

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

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.

推荐答案

要更改 Pandas 的标签 df.plot() 使用 ax.legend([...]):

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

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

另一种方法是通过 plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

这篇关于修改pandas条形图的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆