Editing legend labels

Hello,

I have a problem with the way the legend labels are handled, certainly due
to my poor knowledge of matplotlib internals.

Here an example (matplotlib-1.4.3, py-2.7):

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

At this point I have no idea how to retrieve the list of shown labels, i.e.
['C', 'D'].
What am I missing? What other method should I use?

Thanks in advance
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/matplotlib-users/attachments/20160126/4e414f74/attachment.html>

Hello,

I have a problem with the way the legend labels are handled, certainly
due to my poor knowledge of matplotlib internals.

Here an example (matplotlib-1.4.3, py-2.7):

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

At this point I have no idea how to retrieve the list of shown labels,
i.e. ['C', 'D'].
What am I missing? What other method should I use?

You can do this:

leg = plt.legend(['C', 'D'])
labels = [t.get_text() for t in leg.get_texts()]

Eric

···

On 2016/01/26 1:24 AM, Lorenzo De Leo wrote:

Thanks in advance

_______________________________________________
Matplotlib-users mailing list
Matplotlib-users at python.org
Matplotlib-users Info Page