等高线图的 legend() 为空;这是设计使然吗?

legend() is empty for contour plot; is this by design?

我写了

fig2 = plt.figure(figsize=plt.figaspect(2. / 3.))
ax = fig2.add_subplot(1, 1, 1)
cs = ax.contour(X, Y, distances_bulk, 8)
plt.sca(ax)
plt.legend()

得到了

即右上角的小空东西而不是图例(我用红色三角形标记)。这是设计使然吗?如何获得等高线图的图例(即带有值)?

Python为3.7或3.8,matplotlib为3.3.1

我认为 matplotlib 的作者希望将级别放在内联中,而不是图例。参见 Contour Demo

也就是说,contour 返回的对象包含对艺术家和级别值的引用,因此您可以使用它来创建图例:

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, levels=7)

h = CS.collections
l = [f'{a:.1f}' for a in CS.levels]
ax.legend(h,l)