Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a background image to a plot

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.

like image 329
YXD Avatar asked Mar 01 '13 14:03

YXD


People also ask

How do you change the background of a graph in Python?

We can set the Inner and Outer colors of the plot. set_facecolor() method is used to change the inner background color of the plot. figure(facecolor='color') method is used to change the outer background color of the plot.


2 Answers

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  np.random.seed(0) x = np.random.uniform(0.0,10.0,15) y = np.random.uniform(0.0,10.0,15)  datafile = 'lena.jpg' img = plt.imread(datafile) plt.scatter(x,y,zorder=1) plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0]) plt.show() 

enter image description here

  • For cases where it's desired to have an image in a small area of the scatter plot, change the order of the plots (.imshow then .scatter) and change the extent values.
plt.imshow(img, zorder=0, extent=[3.0, 5.0, 3.0, 4.50]) plt.scatter(x, y, zorder=1) plt.show() 

enter image description here

like image 147
David Zwicker Avatar answered Sep 20 '22 00:09

David Zwicker


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.

like image 38
heltonbiker Avatar answered Sep 24 '22 00:09

heltonbiker