Ben D
Ben D

Reputation: 33

Display image within Matplotlib plot between given XY bounds

I have implemented a numerical model from a journal paper and want to plot my version over a screenshot of a graph from the journal paper pdf using Python and Matplotlib. I took a screenshot of the plot in the paper pdf and cropped it to the bounds (x1,y1) and (x2,y2), measured in millimeters and Newtons. The plot can be any format (jpg, png, whatever).

Now, I want to display that image behind a region of plot in Matplotlib with total figure dimensions ranging from (0,0) to (x3,y3), again measured in millimeters and Newtons, respectively. The image only occupies a subset of the space on the plot, and should be scaled to fit the box defined by the bounds (x1,y1) and (x2,y2). The bounds (x1,y1) and (x2,y2) do not necessarily match the original aspect ratio of the image, so the image must be scaled independently in x and y to fit. I don't want my plots to be tied to the original aspect ratio of the plot within the source image.

How can one map this image into physical space on a plot?

Upvotes: 2

Views: 2709

Answers (1)

Joe Kington
Joe Kington

Reputation: 284752

Basically, use the extent kwarg to imshow. If you want the aspect ratio not to be set to 1, you'll also want autoscale='auto'.

As a quick example:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

x = np.linspace(2, 8, 100)
y = np.cos(x)

x1, x2 = 3, 5.6
y1, y2 = -2.8, 9.6
im = np.array(Image.open('grace_hopper.jpg'))

fig, ax = plt.subplots()
ax.imshow(im, extent=[x1, x2, y1, y2], aspect='auto', cmap='gray')
ax.plot(x, y)
plt.show()

enter image description here

Upvotes: 2

Related Questions