gpt4 book ai didi

python - 如何为 'plt.contour' 中的曲线添加图例条目?

转载 作者:行者123 更新时间:2023-12-01 23:14:09 25 4
gpt4 key购买 nike

基于这个问题,How to plot a function ax^2+bxy+cy^2+d=0 in Python? .我引用了@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:

最佳答案

answer from 2021不再适用于 Matplotlib 3.5.2。它不会正确呈现:

enter image description here

enter image description here

相反,我们应该使用带有自定义标签的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()

它将产生正确的结果:

enter image description here

enter image description here

关于python - 如何为 'plt.contour' 中的曲线添加图例条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69294316/

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