在图表上更改背景图像
我想要更换图表的背景图片。经过一些研究,我找到了这个方法:
img = imread("name.jpg")
plt.scatter(x,y,zorder=1)
plt.imshow(img,zorder=0)
plt.show()
这个方法运行得很好,能在窗口中显示图表。不过,我发现当我想把图表保存到文件时,这个方法就不管用了。
我有这样的代码:
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)
我应该把背景的调用放在哪里呢?这是个常见的问题,还是说我之前的调用覆盖了背景的更改?谢谢大家的帮助。
1 个回答
4
嗯……这可能是你图形的范围设置有问题。这里有个例子:
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')
关键是要在设置好坐标轴的范围后再绘制图像。如果你先绘制图像,可能会导致图像被缩放到坐标轴区域之外的地方。此外,使用 aspect='auto'
可以确保图像不会改变宽高比。(当然,图像会被拉伸以填满整个区域。)如果需要的话,你可以设置 zorder
,但在这个例子中并不需要。