pythonnumpymatplotlibcontour

Overlay contour plot on imshow


I am having trouble producing an overlay with contour plot and 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()

The resulting picture has the contour plot forced into the bottom left hand corner:

https://i.sstatic.net/p7Dtf.png

How is it possible to get a contour overlay on top of the image?


Solution

  • You need to set the extent of the imshow, so that the coordinates line up with those used in the contour plot.

    From the 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.

    So you could use:

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

    enter image description here