You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为matplotlib contour绘制的等值线添加图例标签?

contour绘制等值线添加图例的解决方法

错误原因

plt.contour() 方法本身不支持直接传入label参数,你传入的label会被识别为无效关键字参数,触发警告,也无法正常生成图例。

单条等值线(你的场景)修正代码

import numpy as np
import matplotlib.pyplot as plt

def f(x,y):
    return 0.01*x**2+0.008*x*y-0.013*y**2+0.15*x+0.003*y+1.0097

x = np.arange(-10.0,10.0,0.1)
y = np.arange(-10.0,10.0,0.1)
X, Y = np.meshgrid(x,y)
# 接收contour返回的ContourSet对象
cs = plt.contour(x, y, f(X, Y), [0])
# 为唯一的等值线设置标签
cs.collections[0].set_label('class 1')
plt.legend()
plt.show()

多条等值线场景适配

如果需要同时绘制多条不同阈值的等值线,可以遍历ContourSet的collections属性逐个绑定标签:

cs = plt.contour(x, y, f(X, Y), levels=[-0.5, 0, 0.5])
level_labels = ['阈值-0.5', '阈值0', '阈值0.5']
for line, label in zip(cs.collections, level_labels):
    line.set_label(label)
plt.legend()

内容的提问来源于stack exchange,提问作者Hermi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:45:05