使用同一个Python脚本保存两张图像到两个不同文件中

1 投票
2 回答
3280 浏览
提问于 2025-04-17 16:43

如何用同一个Python脚本把两张图片保存到两个不同的文件里。这两张输出的图片分别是相关性矩阵和一个图表。我当时使用的是matplotlib。

imshow(matrix, interpolation='bilinear')
colorbar()
savefig('/home/sudipta/Downloads/phppython/'+ filename +'.png')
x = range(-width, width)
plt.plot(x, avg_vec)
plt.savefig('/home/sudipta/'+ filename +'plot' +'.png')

当我运行这个脚本时,图形会重叠在一起。但是,我需要的是两张独立的图片。最开始,我尝试把这些图片保存在同一个文件夹里。我想可能是这个地方出了问题。然后我又试着把它们保存在不同的文件夹里,但还是没有成功。

2 个回答

-1
#plot your first image
pyplot.savefig('filename.ext') # ext is your chosen filetype. jpg, png, etc.

#plot your second image
pyplot.savefig('filename2.ext')

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

4

我觉得你应该在中间加上 pyplot.clf()。

#plot your first image
pyplot.savefig('filename.ext') # ext is your chosen filetype. jpg, png, etc.

# clear the plot
pyplot.clf()

# plot your second image
pyplot.savefig('filename2.ext')

这个 clf(清空图形)函数会把你正在绘制的当前图表上的所有东西都清除掉。

另外一个选择是创建两个不同的图形对象。

# create figures and axes
fig0 = pyplot.figure()
ax0 = fig0.add_subplot(1, 1, 1)
fig1 = pyplot.figure()
ax1 = fig1.add_subplot(1, 1, 1)

# draw on ax0, e.g. with ax0.plot(...)
# draw on ax1

fig0.savefig('fig0.png')
fig1.savefig('fig1.png')

撰写回答