修改 pandas 条形图的图例
Posted
技术标签:
【中文标题】修改 pandas 条形图的图例【英文标题】:Modify the legend of pandas bar plot 【发布时间】:2016-01-13 23:08:11 【问题描述】:当我用 pandas 制作条形图并且想更改图例中标签的名称时,我总是很困扰。例如考虑这段代码的输出:
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 独立绘制每一列并自己设置标签。谢谢。
【问题讨论】:
您使用的是哪个版本,python
、pandas
和 matplotlib
。当我运行我的时,我没有看到这个问题。
python:2.7 matplotlib:1.3.1 pandas:0.13.1
你可以试试legend(df.columns)
与第二个结果相同(显然,带有'A'和'B'作为标签)
好的,我只是在测试您是否指定legend()
是原因,因为它对我来说工作正常,而且似乎确实如此。升级 matplotlib 和 pandas 会是个问题吗?
【参考方案1】:
要更改 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([...])
:
import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);
【讨论】:
嗨!我知道这已经快五年了,但我想知道你是否碰巧知道你用于图表的颜色?我真的很喜欢他们,但似乎无法完全匹配他们,谢谢! @RichardRobinson 颜色是'348ABD','7A68A6','A60628','467821','CF4457','188487','E24A33',正确的使用方法是通过@ 987654330@ 配置文件。如果您尝试 google,您会发现许多不错的现成配置。【参考方案2】:如果需要调用plot multiply次数,也可以使用“label”参数:
ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')
虽然在 OP 问题中不是这种情况,但如果 DataFrame
是长格式并且您在绘图前使用 groupby
,这可能会有所帮助。
【讨论】:
仅当您将列作为 y 参数提及时才有效。【参考方案3】:这只是一个边缘案例,但我认为它可以为其他答案增加一些价值。
如果您向图表添加更多详细信息(例如注释或线条),您很快就会发现当您在轴上调用图例时它是相关的:如果您在脚本底部调用它,它将捕获不同的图例元素的句柄,搞砸了一切。
例如以下脚本:
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)
这就是你会得到的:
【讨论】:
以上是关于修改 pandas 条形图的图例的主要内容,如果未能解决你的问题,请参考以下文章