6

Is there a way to clear matplotlib labels inside a graph's legend? This post explains how to remove the legend itself, but the labels themselves still remain, and appear again if you plot a new figure. 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"]

Community
  • 1
  • 1
Alex
  • 3,946
  • 11
  • 38
  • 66

1 Answers1

5

Use set_visible() method:

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

Serenity
  • 35,289
  • 20
  • 120
  • 115
  • Thanks! Do you know if there is a way to access the labels attribute of the legend directly? It would still be best if I could set it to some value manually. – Alex Aug 01 '16 at 21:11
  • 1
    Like here: `for text in legend.texts: if (text.get_text() == 'a'): text.set_text('cc')` – Serenity Aug 01 '16 at 21:29