[英]How to put contour labels as legend in a plot in Python?
我正在绘制轮廓,使用此链接中的示例(下面的代码和输出图) https://www.geeksforgeeks.org/matplotlib-pyplot-contour-in-python/
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
CS1 = plt.contour(X, Y, Z)
fmt = {}
strs = ['1', '2', '3', '4', '5', '6', '7']
for l, s in zip(CS1.levels, strs):
fmt[l] = s
plt.clabel(CS1, CS1.levels, inline = True,
fmt = fmt, fontsize = 10)
plt.title('matplotlib.pyplot.contour() Example')
plt.show()
我希望每个轮廓的标签作为角落的图例,而不是沿着轮廓线。 有办法吗?
for i in range(len(cl)):
CS1.collections[i].set_label(cl[i].get_text())
为您的轮廓创建自定义图例。
label.remove()
迭代地删除标签下面是最终代码的样子:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
CS1 = plt.contour(X, Y, Z)
fmt = {}
strs = ['1', '2', '3', '4', '5', '6', '7']
for l, s in zip(CS1.levels, strs):
fmt[l] = s
cl=plt.clabel(CS1, CS1.levels,fmt=fmt, inline = False, fontsize = 10)
plt.title('matplotlib.pyplot.contour() Example')
for i in range(len(cl)):
CS1.collections[i].set_label(cl[i].get_text())
for label in cl:
label.remove()
plt.legend()
输出给出:
尝试这个:
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
CS1 = plt.contour(X, Y, Z)
nm, lbl = CS1.legend_elements()
lbl_ = [i for i in range(1, len(lbl))]
plt.legend(nm, lbl_)
plt.title('matplotlib.pyplot.contour() Example')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.