Python matplotlib 情节和 imshow

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3497578/
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-18 11:27:24  来源:igfitidea点击:

matplotlib plot and imshow

pythonmatplotlib

提问by user422100

The behavior of matplotlib's plot and imshow is confusing to me.

matplotlib 的情节和 imshow 的行为让我感到困惑。

import matplotlib as mpl
import matplotlib.pyplot as plt

If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the first figure that gets opened, and then call plt.imshow(i), a new figure is displayed without ever calling plt.show().

如果我在调用 plt.imshow(i) 之前调用 plt.show(),则会导致错误。如果我在调用 plt.show() 之前调用 plt.imshow(i),则一切正常。但是,如果我关闭打开的第一个图形,然后调用 plt.imshow(i),则会显示一个新图形,而无需调用 plt.show()。

Can someone explain this?

有人可以解释一下吗?

采纳答案by Joe Kington

If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly.

如果我在调用 plt.imshow(i) 之前调用 plt.show(),则会导致错误。如果我在调用 plt.show() 之前调用 plt.imshow(i),则一切正常。

plt.show()displays the figure (and enters the mainloop of whatever gui backend you're using). You shouldn't call it until you've plotted things and want to see them displayed.

plt.show()显示图形(并进入您正在使用的任何 gui 后端的主循环)。在您绘制事物并希望看到它们显示之前,您不应该调用它。

plt.imshow()draws an image on the current figure (creating a figure is there isn't a current figure). Calling plt.show()before you've drawn anything doesn't make any sense. If you want to explictly create a new figure, use plt.figure().

plt.imshow()在当前图形上绘制图像(如果没有当前图形,则创建图形)。plt.show()在绘制任何东西之前调用没有任何意义。如果要显式创建新图窗,请使用plt.figure().

...a new figure is displayed without ever calling plt.show().

...显示一个新图形,而无需调用 plt.show()。

That wouldn't happen unless you're running the code in something similar to ipython's pylab mode, where the gui backend's mainloop will be run in a seperate thread...

除非您以类似于 ipython 的 pylab 模式运行代码,否则不会发生这种情况,其中 gui 后端的主循环将在单独的线程中运行...

Generally speaking, plt.show() will be the last line of your script. (Or will be called whenever you want to stop and visualize the plot you've made, at any rate.)

一般来说, plt.show() 将是脚本的最后一行。(或者,无论如何,只要您想停止并可视化您所做的绘图,就会调用它。)

Hopefully that makes some more sense.

希望这更有意义。