Examples of how to plot a point or a line in front of a imshow figure in matplotlib
Superimpose a point and imshow
Goal: find and plot a point corresponding to a global minima
import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)plt.imshow(z,origin='lower')plt.colorbar()i,j = np.unravel_index(z.argmin(), z.shape)plt.scatter(i,j,color='r')plt.xlim(0,100)plt.ylim(0,100)plt.title('Draw a point on an image with matplotlib (2/2)')plt.savefig("draw_on_image_01.png")plt.show()plt.close()
Superimpose a point and imshow using the option extent
Example of how to superimpose a point and imshow using matpllotlib

import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)plt.imshow(z,extent=[-1,1,-1,1],origin='lower')plt.colorbar()i,j = np.unravel_index(z.argmin(), z.shape)x = ( i * 2.0 ) / 100.0 - 1.0y = ( j * 2.0 ) / 100.0 - 1.0plt.scatter(x,y,color='r')plt.xlim(-1.0,1.0)plt.ylim(-1.0,1.0)plt.title('Draw a point on an image with matplotlib \n (case 2 with extent)')plt.savefig("draw_on_image_03.png")plt.show()
Superimpose a line and imshow
Example of how to superimpose a line and imshow using matpllotlib

import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)plt.imshow(z,extent=[-1,1,-1,1],origin='lower')plt.colorbar()i,j = np.unravel_index(z.argmin(), z.shape)x = ( i * 2.0 ) / 100.0 - 1.0y = ( j * 2.0 ) / 100.0 - 1.0plt.axvline(x=x,color='red')plt.axhline(y=y,color='red')plt.xlim(-1.0,1.0)plt.ylim(-1.0,1.0)plt.title('Draw a line on an image with matplotlib')plt.savefig("draw_on_image_04.png")plt.show()
References
| Links | Site |
|---|---|
| How do you get the marker squares to be exact squares with matplotlib? | stackoverflow |
| matplotlib: limits when using plot and imshow in same axes | stackoverflow |
| How to get the index of a maximum element in a numpy array along one axis | stackoverflow |
| Python: get the position of the biggest item in a numpy array | stackoverflow |
