【问题标题】:Pandas bar plot with specific colors and legend location?具有特定颜色和图例位置的熊猫条形图?
【发布时间】:2012-07-05 15:59:54
【问题描述】:

我有一个熊猫 DataFrame,我想绘制一个包含图例的条形图。

import pylab as pl
from pandas import *

x = DataFrame({"Alpha": Series({1: 1, 2: 3, 3:2.5}), "Beta": Series({1: 2, 2: 2, 3:3.5})})

如果我直接调用 plot,那么它会将图例放在 plot 之上:

x.plot(kind="bar")

如果我在图中关闭图例并尝试稍后添加它,那么它不会保留与 DataFrame 中的两列关联的颜色(见下文):

x.plot(kind="bar", legend=False)
l = pl.legend(('Alpha','Beta'), loc='best')

在 Pandas DataFrame 的 matplotlib 图中包含图例的正确方法是什么?

【问题讨论】:

    标签: python legend pandas


    【解决方案1】:

    最简洁的方法是:

    x.plot(kind="bar").legend(bbox_to_anchor=(1.2, 0.5))
    

    一般来说

    x.plot(kind="bar").legend(*args, **kwargs)
    

    【讨论】:

    • 这是最好的答案。
    • @AliHashemi 这不是被接受的答案的原因是因为它没有回答原始问题,这也是如何设置特定颜色。这个答案没有显示如何做到这一点。顺便说一句,Wes McKinneypandas 的主要作者。
    【解决方案2】:

    如果要手动添加图例,则必须向子图询问条形图的元素:

    In [17]: ax = x.plot(kind='bar', legend=False)
    
    In [18]: patches, labels = ax.get_legend_handles_labels()
    
    In [19]: ax.legend(patches, labels, loc='best')
    Out[19]: <matplotlib.legend.Legend at 0x10b292ad0>
    

    另外,plt.legend(loc='best')ax.legend(loc='best') 应该“正常工作”,因为在制作绘图时已经设置了条形图补丁的“链接”,因此您不必传递轴列表标签。

    我不确定您使用的 pandas 版本是否返回子图的句柄 (ax = ...),但我相当肯定 0.7.3 会。您可以随时通过 plt.gca() 获得对它的引用。

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2020-10-22
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2017-12-30
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多