如何清除图例中的matplotlib标签?

时间:2016-08-01 20:48:17

标签: python matplotlib legend

有没有办法在图表的图例中清除matplotlib标签? This post解释了如何删除图例本身,但标签本身仍然存在,如果您绘制新图形,则会再次出现。我尝试了以下代码,但它不起作用:

filename

编辑:这是一个例子

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

输出: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)

1 个答案:

答案 0 :(得分:2)

使用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