27
votes

Say I am plotting a set of points with an image as a background. I've used the Lena image in the example:

import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread

np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)
img = imread("lena.jpg")
plt.scatter(x,y,zorder=1)
plt.imshow(img,zorder=0)
plt.show()

This gives meenter image description here .

My question is: How can I specify the corner coordinates of the image in the plot? Let's say I'd like the bottom-left corner to be at x, y = 0.5, 1.0 and the top-right corner to be at x, y = 8.0, 7.0.

2
from scipy.misc import imread does not work for me. Instead one can also use stackoverflow.com/questions/5073386/… - toom
@toom you probably have an old version of SciPy - YXD
Hmm, I using scipy version '0.12.0'. This version does not seem to be too old it is from Sep. 2013 ( sourceforge.net/projects/scipy/files/scipy ). I installed it on my mac via brew. - toom

2 Answers

38
votes

Use the extent keyword of imshow. The order of the argument is [left, right, bottom, top]

import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread
import matplotlib.cbook as cbook

np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)

datafile = cbook.get_sample_data('lena.jpg')
img = imread(datafile)
plt.scatter(x,y,zorder=1)
plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.show()
11
votes

You must use the extent keyword parameter:

imshow(img, zorder=0, extent=[left, right, bottom, top])

The elements of extent should be specified in data units so that the image can match the data. This can be used, for example, to overlay a geographical path (coordinate array) over a geo-referenced map image.