Home > database >  Overlay contour plot on imshow
Overlay contour plot on imshow

Time:11-09

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://img.codepudding.com/202111/2ab247360e4c408bace1b94bf5017faf.png

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

CodePudding user response:

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

From the enter image description here

CodePudding user response:

Since you are not displaying x,y coordinates, another option is to remove X,Y arguments in contour, so that that coordinates are running from 0 to n

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

Output:

enter image description here

  • Related