在 imshow 上叠加等高线图

Overlay contour plot on imshow

我在使用等高线图和 imshow 生成叠加层时遇到问题。

import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3 ) * np.exp(-x ** 2 - y ** 2)

n = 100
x = np.linspace(-3, 3, 3 * n)
y = np.linspace(-3, 3, 3 * n)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.figure(figsize=(8,6))
plt.imshow(Z, interpolation='nearest', cmap=plt.cm.hot, origin='lower')
contours = plt.contour(X, Y, f(X,Y), 10, colors='black')
plt.clabel(contours, inline=1, fontsize=10)
plt.xticks([])
plt.yticks([])
plt.savefig('overlay_image.pdf', dpi=72)
plt.show()

生成的图片的等高线图被强制置于左下角:

如何在图像上叠加轮廓?

您需要设置 imshow 的范围,以便坐标与 contour 图中使用的坐标对齐。

来自imshow docs

extent : floats (left, right, bottom, top), optional

The bounding box in data coordinates that the image will fill. The image is stretched individually along x and y to fill the box.

所以你可以使用:

extent = x.min(), x.max(), y.min(), y.max()
plt.imshow(Z, interpolation='nearest', 
           cmap=plt.cm.hot, origin='lower',
           extent=extent)

由于您不显示 x,y 坐标,另一种选择是删除 contour 中的 X,Y 参数,这样坐标就是 0 中的 运行 ] 到 n

plt.imshow(Z, interpolation='nearest', cmap=plt.cm.hot, origin='lower')
contours = plt.contour(f(X,Y), 10, colors='black')

输出: