Reputation: 3627
Given that I have a line object in matplotlib, how do I get what the legend label will be for that line?
The get_label()
method of the Artist class only works if the legend did not change or create the label (using plt.legend()
or similar).
Getting the handler associated with a line is possible using Legend.get_legend_handler()
, but that isn't associated with any text. Legend.get_lines()
gives a list of line objects... but they aren't the same objects that are plotted.
An example of how get_label()
doesn't work:
x = [0,1]
y = [1,1]
line, = plt.plot(x,y)
plt.legend(("hello",))
plt.plot()
line.get_label() # returns '_line0'
Does anyone have any ideas?
Upvotes: 5
Views: 16270
Reputation: 339120
There is no general way of knowing if a legend contains a label for a given artist. The artist can have a custom label or not and this does not neccesarily need to coincide with the label used in the legend.
A solution will therefore always depend on assumptions.
A. If we assume that the artists are given a label and that this label is the one shown in the legend, the solution is easy:
line.get_label()
B. If we assume that the order by which the lines are created is the same as they appear in the legend and that no other artists are put in between, we could do
def get_label_for_line(line):
leg = line.axes.get_legend()
ind = line.axes.get_lines().index(line)
return leg.texts[ind].get_text()
C. If we assume that the legend has been created directly from the artists (and not other proxy artists), we can compare the label, like
def get_label_for_line(line):
leg = line.axes.get_legend()
for h, t in zip(leg.legendHandles, leg.texts):
if h.get_label() == line.get_label():
return t.get_text()
For other solutions, one would need to know more about how exactly the figure, its artists and the legend are created.
Upvotes: 10