将多个图形保存到单独的文件中是行不通的,即使它们正确显示()

Saving multiple figures to separate files is not working even if they show() properly

我试图生成两个不同的图形来分隔使用相同基本数据的文件(.png 图像),但我得到的是空白图像。但是,当在带有 plt.show() 语句的 jupyter 笔记本中显示时,这两个数字看起来都不错。 我的相关代码如下:

plt.figure(1)
fig1, axs1 = plt.subplots(2,2)
plt.figure(2)
fig2, axs2 = plt.subplots(2,2)

# generate 4 datasets in a for loop
for i in range(4): 
    x,y = createRandomData(parameters)
    fit1 = doFit1(x,y)
    plt.figure(1)
    axs1[i//2,i%2].plot(x,y,color='black',linewidth = 1)
    axs1[i//2,i%2].plot(x,fit1,color='green',linewidth = 1)
    fit2 = doFit2(x,y)
    plt.figure(2)
    axs2[i//2,i%2].plot(x,y,color='black',linewidth = 1)
    axs2[i//2,i%2].plot(x,fit1,color='green',linewidth = 1)
plt.figure(1)
plt.gcf().set_size_inches(12,8)
plt.gcf().savefig('dataWithFit1.png', dpi=200)
plt.show()
plt.figure(2)
plt.gcf().set_size_inches(12,8)
plt.gcf().savefig('dataWithFit2.png', dpi=200)
plt.show()

无法弄清楚为什么 savefig() 不产生正确的输出,即使以下 show() 语句在 jupyter notebook 中向浏览器产生正确的输出。

我也试过变量 fig1 而不是 plt.gcf()

有什么建议吗?

感谢@Patol75 的评论,我已将代码修改为:

fig1, axs1 = plt.subplots(2,2)
fig2, axs2 = plt.subplots(2,2)

# generate 4 datasets in a for loop
for i in range(4): 
    x,y = createRandomData(parameters)
    fit1 = doFit1(x,y)
    axs1[i//2,i%2].plot(x,y,color='black',linewidth = 1)
    axs1[i//2,i%2].plot(x,fit1,color='green',linewidth = 1)
    fit2 = doFit2(x,y)
    axs2[i//2,i%2].plot(x,y,color='black',linewidth = 1)
    axs2[i//2,i%2].plot(x,fit2,color='green',linewidth = 1)
fig1.set_size_inches(12,8)
fig1.savefig('dataWithFit1.png', dpi=200)
fig1.show()
fig2.set_size_inches(12,8)
fig2.savefig('dataWithFit2.png', dpi=200)
plt.show()

最后一个绘图命令也有一个拼写错误(应该绘制 fit2 而不是 fit1)是在 "pseudofying" post 的代码时引入的。

现在可以正确显示和保存图形了。但是,我仍然收到警告 UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure. 在 jupyter 笔记本中。因此,如果你们中有人对此有任何见解,请务必添加评论以确保完整性。