为什么我的plt.savefig不工作?

2024-06-13 23:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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)

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

谢谢。


Tags: andthetestimportpdfplotsaveas
3条回答

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

您应该在调用savefig之前调用savetxtshow

无法生成绘图,因为您定义的列表axis_x只有长度9,而grdgrd2的长度等于10。 只需将axis_x的定义替换为:

axis_x=range(1,11) 你的情节会出现,它会被保存好。

我遇到了同样的问题,解决方法是将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()

相关问题 更多 >