Python 为什么我的 plt.savefig 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30765455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:55:39  来源:igfitidea点击:

Why is my plt.savefig is not working?

pythonnumpymatplotlib

提问by Jika

I have a simple python code as follows:

我有一个简单的python代码如下:

import numpy as np
import matplotlib.pyplot as plt

"""
Here are the solutions and the plot.
"""

# Create the axis and plot.
plt.axis([0, 10, 0, 10])
axis_x = range(1, 11)
grd = [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1]
grd2 = [1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2]
plt.plot(axis_x, grd, '-g', label='BR1')
plt.plot(axis_x, grd2, '-b', label='BR2')
plt.legend(loc='upper left')
plt.grid()
plt.show()

# Save the results vector to a text file.
np.savetxt('test.out', (grd, grd2))

# Save the figure as '.eps' file.
plt.savefig('expl.pdf', format='pdf', dpi=1200)

When I open the output files expl.pdfand/or test.outI find them blank and nothing in there. Why?

当我打开输出文件expl.pdf和/或test.out我发现它们是空白的,里面什么也没有。为什么?

Thanks.

谢谢。

采纳答案by shx2

When you close the image displayed by plt.show(), the image is closed and freed from memory.

当您关闭由 显示的图像时plt.show(),图像将关闭并从内存中释放。

You should call savefigand savetxtbefore calling show.

你应该在调用savefigsavetxt之前调用show

回答by xecafe

Your plot cannot be generated because you defined the list axis_xhaving only the length 9, while grdand grd2have the length equal to 10. Just replace the definition of axis_xwith:

无法生成您的情节,因为你所定义的列表axis_x只具有长度为9,而grdgrd2有长度等于10只需更换的定义axis_x有:

axis_x=range(1,11)and your plot will show up and it will be saved OK.

axis_x=range(1,11)并且您的绘图将显示出来,并且可以正常保存。

回答by bmc

I just ran into the same issue and the resolution was to put the savefig command before the plt.show()statement, but specify the filetype explicitly. Here is my code:

我刚刚遇到了同样的问题,解决方案是将 savefig 命令放在plt.show()语句之前,但明确指定文件类型。这是我的代码:

plt.suptitle("~~~~")
plt.title("~~~~")
ax = sns.boxplot(x=scores_df.score, y=scores_df.response)
plt.savefig("test.png", **format="png"**)
plt.show()

plt.close()