Plot over an image background in python [duplicate]

I would like to plot a graph over an image background using matplotlib. I found how to do it in matlab http://www.peteryu.ca/tutorials/matlab/plot_over_image_background

I've tried something basic like this:

im = plt.imread("dd.png")
implot = plt.imshow(im)
theta=np.linspace(0,2*np.pi,50)
z=np.cos(theta)*39+145
t=np.sin(theta)*39+535-78+39
plt.plot(z,t)
plt.show()

but it gave me something really ugly:

something really ugly


Just like in the MATLAB example that you linked to, you have to specify the desired extent of the image when you call in imshow.

By default, matplotlib and MATLAB both place the upper left corner of the image the origin, go down and to the right from there, and set each pixel as a 1x1 square in coordinate space. This is what your image is doing.

You can control this with the extent parameter which takes the form of a list [left, right, bottom, top].

Not using extent looks like this:

import matplotlib.pyplot as plt
img = plt.imread("airlines.jpg")
fig, ax = plt.subplots()
ax.imshow(img)

enter image description here

You can see that we have a 1600 x 1200 of Samuel L. Jackson getting, quite frankly, rather annoyed with the snake aboard his airline flight.

But if we want to plot a line ranging from 0 to 300 in both dimension over this, we can do just that:

fig, ax = plt.subplots()
x = range(300)
ax.imshow(img, extent=[0, 400, 0, 300])
ax.plot(x, x, '--', linewidth=5, color='firebrick')

enter image description here

I don't know if the line will help Mr. Jackson with his snake problem. At the very least, it won't make things any harder.