Skip to content Skip to sidebar Skip to footer

Changing Background Image On A Plot

I want to change the background image of a graph. After some researches I've found this method: img = imread('name.jpg') plt.scatter(x,y,zorder=1) plt.imshow(img,zorder=0) plt.show

Solution 1:

Hmmm... It could be a problem with the extents of your figure. Here is an example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
# a plot
t = np.linspace(0,2*np.pi,1000)
ax.plot(t * np.sin(t), t * np.cos(t), 'w', linewidth=3)
ax.plot(t * np.sin(t), t * np.cos(t), 'k', linewidth=1)

# create a  background image
X = np.linspace(0, np.pi, 100)
img = np.sin(X[:,None] + X[None,:])

# show the background image
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.imshow(img, extent=[x0, x1, y0, y1], aspect='auto')

fig.savefig('/tmp/test.png')

The point is to draw the image after the axis extents have been set. If you draw it first, it may be scaled into some place far away from what your axis area is. Also, using the aspect='auto' ensures the image is not trying to change the aspect ratio. (Naturally, the image will get stretched to fill the whole area.) You may set the zorder if needed, but in this example it is not needed.

enter image description here

Post a Comment for "Changing Background Image On A Plot"