python - 为图例后绘图添加标签

标签 python matplotlib legend

我必须绘制两条线,然后测量它们之间的绝对距离。该距离随后成为图例的标签。 伪代码看起来像这样:

for line in file:
    # extract data here
    sample = sns.kdeplot(data)
    perfect_template = sns.kdeplot(perfect_template_data)
    sample_line = sample.get_lines()[iterate].get_data()
    perfect_line = perfect_template.get_lines()[iterate]get_data()
    absolute_diff = sum(abs(np.diff(zip(sample_line, perfect_line))))
    label = absolute_diff
    sample = sns.kdeplot(data, linewidth=1, label=label)
    plt(legend)
pp.savefig()

这需要我绘制 sns.kdeplot 两次。 有没有办法将标签添加到初始 sns.kdeplot 而不重新绘制?

最佳答案

您可以像这样使用set_label():

sample.set_label(label)

即举一个最小的例子:

x = np.linspace(0, 2*np.pi)
y = np.sin(x)
y2 = np.sin(2*x)

first_line,  = plt.plot(x, y)
plt.plot(x, y2)

first_line.set_label('First line')

plt.legend()

关于python - 为图例后绘图添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32526324/

相关文章:

python - 其他应用程序中的 Django 迁移文件?

python - 使用 Python,获取 zip 存档中的文件名

python - 如何在 Python Seaborn 的线图中的每个标记上添加值/标签?

python - 是否可以更新动画中的 matplotlib 箭袋位置坐标?

r - ggplot2 直方图图例太大

python - 将比较应用于 Python 中的列表?

python - Django 中的 Zeromq PUSH/PULL

python - 设置导航工具栏和拾取事件的顶级轴

java - 如何对 JFreeChart 中的图例进行排序?

matplotlib - Matplotlib 中相交透明层的正确图例颜色