Matplotlib编辑图例标签

时间:2016-01-27 09:45:23

标签: python matplotlib

如果我使用plt.legend([some labels])修改地块的标签,然后拨打ax.get_legend_handles_labels(),我会找回旧标签。

这是一个简单的例子:

In [1]: import matplotlib.pyplot as plt

In [2]: plt.plot([1,2,3], label='A')
Out[2]: [<matplotlib.lines.Line2D at 0x7f60749be310>]

In [3]: plt.plot([2,3,4], label='B')
Out[3]: [<matplotlib.lines.Line2D at 0x7f60749f1850>]

In [4]: ax = plt.gca()

In [5]: l = ax.get_legend_handles_labels()

In [6]: l
Out[6]:
([<matplotlib.lines.Line2D at 0x7f60749be310>,
  <matplotlib.lines.Line2D at 0x7f60749f1850>],
 [u'A', u'B'])

In [7]: plt.legend(['C', 'D'])  ### This correctly modifies the legend to show 'C' and 'D', but then ...
Out[7]: <matplotlib.legend.Legend at 0x7f6081dce190>

In [10]: l = ax.get_legend_handles_labels()

In [11]: l
Out[11]:
([<matplotlib.lines.Line2D at 0x7f60749be310>,
  <matplotlib.lines.Line2D at 0x7f60749f1850>],
 [u'A', u'B'])

此时我不知道如何检索显示的标签列表,即['C', 'D']。 我错过了什么?我应该使用哪种其他方法?

为了给出更多的上下文,我要做的是绘制一个pandas数据帧,修改图例以添加一些信息,然后在同一轴上绘制另一个数据帧并使用标签重复相同的过程。 为了做到这一点,我第二次需要修改图例中标签的PART并保持其余部分不变。

1 个答案:

答案 0 :(得分:1)

执行plt.legend的功能文档中建议的内容可以实现您想要的目标。

  

签名:plt.legend(* args,** kwargs)文档字符串:放置图例   轴。

     

为轴上已存在的线创建图例(通过图表   例如),只需使用可迭代的字符串调用此函数,   每个图例项目一个。例如::

Chart.types.Line.extend({
    name: "LineAlt",
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        var ctx = this.chart.ctx;
        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = 'rgba(0,0,255,0.2)';
        ctx.fillRect(0, 0, this.chart.width, this.chart.height);
        ctx.globalCompositeOperation = 'source-over';
    }
});
     

但是,为了保留“标签”和图例元素实例   在一起,最好在艺术家处指定标签   创作,或通过调用   :math:... new Chart(ctx).LineAlt(data); 方法对艺术家::

ax.plot([1, 2, 3])
ax.legend(['A simple line'])
~matplotlib.artist.Artist.set_label