How to clear matplotlib labels in legend?

柔情痞子 提交于 2021-01-02 06:31:25

问题


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"]


回答1:


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()



来源:https://stackoverflow.com/questions/38707853/how-to-clear-matplotlib-labels-in-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!