How to clear matplotlib labels in a legend?

Is there a way to clear matplotlib labels inside a graph legend? This post explains how to remove a legend, but the shortcuts themselves remain and reappear if you draw a new shape. I tried the following code, but it does not work:

handles, labels = ax.get_legend_handles_labels()
labels = []

EDIT: Here is an example

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca()
ax.scatter([1,2,3], [4,5,6], label = "a")
legend = ax.legend()
plt.show()
legend.remove()
handles, labels = ax.get_legend_handles_labels()
print(labels)

Output: ["a"]

+4
source share
1 answer

Use method set_visible():

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca()
ax.scatter([1,2,3], [4,5,6], label = "a")
legend = ax.legend()
for text in legend.texts:
    if (text.get_text() == 'a'): text.set_text('b') # change label text
    text.set_visible(False)  # disable label
plt.show()

enter image description here

+2
source

Source: https://habr.com/ru/post/1649824/


All Articles