python - Matplotlib editing legend labels -
if modify labels of plot plt.legend([some labels])
, call ax.get_legend_handles_labels()
old labels.
here simple example:
in [1]: import matplotlib.pyplot plt in [2]: plt.plot([1,2,3], label='a') out[2]: [<matplotlib.lines.line2d @ 0x7f60749be310>] in [3]: plt.plot([2,3,4], label='b') out[3]: [<matplotlib.lines.line2d @ 0x7f60749f1850>] in [4]: ax = plt.gca() in [5]: l = ax.get_legend_handles_labels() in [6]: l out[6]: ([<matplotlib.lines.line2d @ 0x7f60749be310>, <matplotlib.lines.line2d @ 0x7f60749f1850>], [u'a', u'b']) in [7]: plt.legend(['c', 'd']) ### correctly modifies legend show 'c' , 'd', ... out[7]: <matplotlib.legend.legend @ 0x7f6081dce190> in [10]: l = ax.get_legend_handles_labels() in [11]: l out[11]: ([<matplotlib.lines.line2d @ 0x7f60749be310>, <matplotlib.lines.line2d @ 0x7f60749f1850>], [u'a', u'b'])
at point have no idea how retrieve list of shown labels, i.e. ['c', 'd']
. missing? other method should use?
to give bit more context, i'm trying plot pandas dataframe, modify legend add information , plot dataframe on same axes , repeat same procedure labels. in order that, second time need modify part of labels in legend , keep rest unchanged.
doing suggested in function doc of plt.legend
accomplishes wanted.
signature: plt.legend(*args, **kwargs) docstring: places legend on axes.
to make legend lines exist on axes (via plot instance), call function iterable of strings, 1 each legend item. example::
ax.plot([1, 2, 3]) ax.legend(['a simple line'])
however, in order keep "label" , legend element instance together, preferable specify label either @ artist creation, or calling :meth:
~matplotlib.artist.artist.set_label
method on artist::line, = ax.plot([1, 2, 3], label='inline label') # overwrite label calling method. line.set_label('label via method') ax.legend()
import matplotlib.pyplot plt line1, = plt.plot([1,2,3], label='a') line2, = plt.plot([2,3,4], label='b') ax = plt.gca() l = ax.get_legend_handles_labels() print(l) line1.set_label("c") line2.set_label("d") ax.legend() l = ax.get_legend_handles_labels() print(l) plt.show() >>([<matplotlib.lines.line2d object @ 0x000000000a399eb8>, <matplotlib.lines.line2d object @ 0x0000000008a67710>], ['a', 'b']) >>([<matplotlib.lines.line2d object @ 0x000000000a399eb8>, <matplotlib.lines.line2d object @ 0x0000000008a67710>], ['c', 'd'])
Comments
Post a Comment