【问题标题】:Why is my plt.savefig is not working?为什么我的 plt.savefig 不起作用?
【发布时间】:2015-08-26 05:50:28
【问题描述】:

我有一个简单的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 时,我发现它们是空白的,里面什么也没有。为什么?

谢谢。

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    当你关闭plt.show()显示的图片时,图片会关闭并从内存中释放出来。

    您应该在致电show 之前致电savefigsavetxt

    【讨论】:

    • 谢谢。现在剧情很好。 test.out 仍然是空的。
    • 正如文档所说“因为关闭图形窗口会从 pyplot 注销它,如果您希望保存图形并查看它,则必须在调用 show 之前调用 savefig。”在matplotlib.org/faq/howto_faq.html 的“使用 show()”部分中。
    【解决方案2】:

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

    plt.suptitle("~~~~")
    plt.title("~~~~")
    ax = sns.boxplot(x=scores_df.score, y=scores_df.response)
    plt.savefig("test.png", format="png") # specify filetype explicitly
    plt.show()
    
    plt.close()
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 发布此答案后,作者修改了axis_x=range(1,11),现在我的答案看起来不合适:)
      猜你喜欢
      • 2018-12-25
      • 2015-09-25
      • 2018-03-05
      • 2013-04-19
      • 2015-10-17
      • 2016-02-20
      • 2023-04-03
      • 2012-01-07
      • 2012-06-11
      相关资源
      最近更新 更多