[英]Modify the legend of pandas bar plot
当我用熊猫制作条形图时,我总是很烦恼,我想更改图例中标签的名称。 例如,考虑此代码的输出:
import pandas as pd
from matplotlib.pyplot import *
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar')
legend(['AAA', 'BBB'])
但我最终得到了这个:
事实上,第一条虚线似乎对应于一个额外的补丁。
所以我想知道这里是否有一个简单的技巧来更改标签,或者我是否需要使用 matplotlib 独立绘制每一列并自己设置标签。 谢谢。
要更改 Pandas df.plot()
的标签,请使用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([...])
做同样的plt.legend([...])
:
import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);
如果您需要调用 plot 乘法次数,您还可以使用“label”参数:
ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')
虽然在 OP 问题中情况并非如此,但如果DataFrame
是长格式并且您在绘图之前使用groupby
,这可能会有所帮助。
这有点边缘情况,但我认为它可以为其他答案增加一些价值。
如果您向图形添加更多细节(例如注释或线条),您很快就会发现当您在轴上调用图例时它是相关的:如果您在脚本底部调用它,它将捕获不同的句柄传奇元素,搞砸了一切。
例如下面的脚本:
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
虽然这是一个玩具示例,可以通过更改命令的顺序轻松修复,但有时您需要在多次操作后修改图例,因此下一个方法将为您提供更大的灵活性。 例如,这里我还更改了图例的字体大小和位置:
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)
这是你会得到的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.