如何为轮廓中的曲线添加图例条目

问题描述 投票:0回答:2

基于这个问题,如何在Python中绘制函数ax^2+bxy+cy^2+d=0?。我引用@Michael Szczesny 的答案中的代码:

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)
plt.contour(x, y, f(X, Y), [0]);

如果我尝试为曲线添加标签

f(X,Y)

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)
plt.contour(x, y, f(X, Y), [0], label='class 1')
plt.legend()
plt.show()

错误:用户警告:轮廓未使用以下 kwargs:

python matplotlib legend contour
2个回答
4
投票

2021 年的 答案 不再适用于 Matplotlib 3.5.2。它不会正确渲染:

相反,我们应该将

legend_elements
与自定义标签一起使用:

import matplotlib.pyplot as plt
import numpy as np

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)
cnt = plt.contour(x, y, f(X, Y), [0])
artists, labels = cnt.legend_elements()
plt.legend(artists, ['class 1'])
plt.show()

# multiple levels
levels = [0, 1, 2, 3]
cnt = plt.contour(x, y, f(X, Y), levels)
artists, labels = cnt.legend_elements()
custom_labels = []
for level, contour in zip(levels, cnt.collections):
    custom_labels.append(f'level {level}')
plt.legend(artists, custom_labels, bbox_to_anchor=[1.01, 1], loc='upper left')
plt.tight_layout()
plt.show()

它将产生正确的结果:


2
投票

Matplotlib 的

contour
的设计理念似乎是绘制颜色条而不是图例。但是,在这种情况下,只有一个级别,可以强制图例为各个轮廓分配标签:

import matplotlib.pyplot as plt
import numpy as np

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)
cnt = plt.contour(x, y, f(X, Y), [0])
cnt.collections[0].set_label('class 1')
plt.legend()
plt.show()

这是具有多个级别的相同方法的示例:

levels = [0, 1, 2, 3]
cnt = plt.contour(x, y, f(X, Y), levels)
for level, contour in zip(levels, cnt.collections):
    contour.set_label('level {level}')
plt.legend(bbox_to_anchor=[1.01, 1], loc='upper left')
plt.tight_layout()
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.