Changing background image on a plot

matplotlib, python, seaborn

Solution

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.

Problem

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() ``` It's works fine and creates a window with the graph inside of it. However I've found that doesn't work when I have to save the graph on a file. I have something like: ``` plt.clf() axe_lim = int(max([abs(v) for v in x_values+y_values])*1.4) plt.plot(x_values, y_values) plt.gcf().set_size_inches(10,10,forward='True') plt.axhline(color='r') plt.axvline(color='r') plt.title(label.upper(), size=25) plt.xlim((-axe_lim,axe_lim)) plt.ylim((-axe_lim,axe_lim)) plt.xlabel(units) plt.ylabel(units) plt.grid(True) plt.tight_layout() img = imread("name.jpg") plt.imshow(img) plt.savefig(plot_pict) ``` Where do I have to put the calls for the background? Is a common issue or the calls I made are overwriting the background changes? Thanks for the help.

Original source