python - 为什么 Matplotlib 中的 pyplot 不允许您在显示图像后保存图像?

标签 python matplotlib

如果我在尝试保存图像之前放置pyplot.show(),则该文件实际上并不包含该图像。

起初我以为这是一个错误,但后来我切换了 pyplot.show()pyplot.savefig('foo5.png') 并且它起作用了。

这是一个示例代码片段。

def plot(embeddings, labels):
  assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
  pyplot.figure(figsize=(20, 20))  # in inches
  for i, label in enumerate(labels):
    x, y = embeddings[i,:]
    pyplot.scatter(x, y)
    pyplot.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
                   ha='right', va='bottom')
  pyplot.savefig('foo4.png')
  pyplot.show()
  pyplot.savefig('foo5.png')

books = [bookDictionary[i] for i in range(1, num_points2+1)]
plot(two_d_embeddings, books)
print( os.listdir() )

foo4.png 很好,但 foo5.png 是空白的。

最佳答案

正如您自己发现的那样,使用 pyplot 您需要在 shown 之前保存图形。

事实上,这仅适用于非交互模式 (ioff),但这是默认且可能是最常见的用例。

发生的情况是,一旦调用pyplot.show(),就会显示图形并启动事件循环,接管 python 偶循环。因此,pyplot.show() 之后的任何命令都会被延迟,直到图形关闭。这意味着 show 之后的 pyplot.savefig() 在图形关闭之前不会执行。一旦图形关闭,pyplot 状态机内就不再保存图形了。

但是,如果需要,您可以保存特定的数字。例如

import matplotlib.pyplot as plt

plt.plot([1,2,3])
fig = plt.gcf()
plt.show()
fig.savefig("foo5.png")

在这里,我们调用特定图形(在本例中是唯一存在的)的 savefig 方法,我们需要为其获取句柄 (fig)图。

请注意,在这种情况下,如果您需要精细控制 matplotlib 的工作方式,那么不使用 pyplot 而是主要依赖面向对象的接口(interface)总是有用的。 因此,

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1,2,3])
plt.show()
fig.savefig("foo5.png")

这是在显示图形后保存图形的更自然的方式。

关于python - 为什么 Matplotlib 中的 pyplot 不允许您在显示图像后保存图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178853/

相关文章:

python - Matplotlib:一条线,以不同单位绘制在两个相关的 x 轴上?

python - 如何将图像存储在变量中

python - 为什么基于矢量的图像文件包含损坏的字符?

python - Matplotlib 1.0.1 至 1.4.2

python - 在 PyGame 中使用 GIF

python - 如何从 Python 脚本执行 Node js 的 pm2 启动/停止/状态?

python - lxml 没有为 HTML 正确解析 unicode

python - tensorflow from_generator() 给出错误 - 'generator` 产生无法转换为预期类型的​​元素

python - PySpark 在嵌套数组中反转 StringIndexer

c# - Matplotlib savefig to BytesIO 是不是有点不对?