gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:27:31 25 4
gpt4 key购买 nike

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

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)

输出:["a"]

最佳答案

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

关于python - 如何清除图例中的 matplotlib 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com