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

Jik*_*ika 22 python numpy matplotlib

我有一个简单的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)
Run Code Online (Sandbox Code Playgroud)

当我打开输出文件expl.pdf和/或test.out我发现它们是空白的,没有任何内容.为什么?

谢谢.

shx*_*hx2 47

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

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


bmc*_*bmc 5

我刚刚遇到了同样的问题,解决方案是将 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()
Run Code Online (Sandbox Code Playgroud)