user3014597
user3014597

Reputation: 91

get_legend_handles_labels() not returning new legend data

This one is blowing my mind. I'm creating a little customize legend function where you put in some text and properties and it'll make it for you. So, before this is reachable in the GUI, a figure with a legend has already been created by this point which has "run5" and "run6" in it.

I wrote something that deletes the existing legend and calls legend on that same axis again with new handles/labels. However, when I do ax.get_legend_handles_labels() right afterwards it returns the deleted legend's handle and labels, completely ignoring the legend call I just did.

I've tried removing the legend and then just recreating it. But clearly ax is holding onto the previous legend's data.

from matplotlib.lines import Line2D

ax = self.axes[ind] #just the axis handle
custom_lines, custom_strings = [], []        
try:
    ax.get_legend().remove()
except:
    # Means no legend exists
    pass
for idx, i in enumerate(self.lgndRowWidget):
    if not i.isHidden():
        #The below five lines are grabbing data from GUI
        lineText  = self.lgndStr[idx].text() # Is "test" here
        lineType  = self.lgndLine[idx].currentText()
        lineWidth = self.lgndWidth[idx].value()
        lineMrkr  = self.lgndMrkr[idx].currentText()
        lineClr   = self.lgndClr[idx].text()

        custom_lines.append(Line2D([0],[0],
                            lw=lineWidth,
                            ls=lineType,
                            marker=lineMrkr,
                            color=lineClr))                                           
        custom_strings.append(lineText)

if len(custom_lines) != 0:
    print(custom_strings)
    self.legList = ax.legend(custom_lines, custom_strings)
    a,b = ax.get_legend_handles_labels()
    print(b)
    self.fig.canvas.draw()

print(custom_strings) returns whatever I input. In this case "test". print(b) returns what was previously in the legend that I can't seem to get rid of: the initial "run5" and "run6". It SHOULD be "test".

Upvotes: 6

Views: 5138

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339695

You might have misunderstood the functionality of ax.get_legend_handles_labels().

What it does is to look for artists (like lines, collections etc.) that have a label. It then returns those artists and their respective labels. Hence ax.legend() is roughly equivalent to

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles, labels=labels)

.get_legend_handles_labels() does not know about whether there is a legend present, because it returns what is supposed to be in the legend, not what currently is in it.

Upvotes: 4

Related Questions