问题描述
因此,我将以下简单代码保存在.py文件中,并在shell中执行:
So I have a following simple code saved in a .py file, and executing in shell:
import matplotlib.pyplot as plt
myfig = plt.figure(figsize=(5, 5))
ax1 = myfig.add_subplot(1, 1, 1)
myfig.show()
但是它在执行时什么也不做,没有错误什么也没有.
However it does nothing upon execution, no errors nothing.
然后,当我在shell中启动Ipython并键入完全相同的代码时,它确实会弹出一个空窗口.为什么会这样?
Then when I start Ipython in shell, and type exact same code, it does pop up an empty window. Why is that?
当然我可以使用plt.show(),一切都很好.但是,可以说我有两个图,Fig1和Fig2,并且两个图中都有东西,而我只想显示其中一个,我该怎么做? plt.show()绘制了它们两者.
of course I can use plt.show() and everything is fine. But lets say I have two figures, fig1 and fig2, and there is stuff in both figs, and I want to only display one of them, how can I do that? plt.show() plots both of them.
对不起,如果这很愚蠢,我只是很好奇为什么在ipython中进行交互工作时,调用fig1.show()时会弹出窗口,但是当我在shell中执行相同的脚本但执行以下操作时却什么也没发生:python myfile.py
Sorry if this is stupid I'm just curious why when working interactively in ipython, window pops up upon calling fig1.show() but nothing happens when I execute same script in shell but doing: python myfile.py
谢谢!
推荐答案
plt.show
启动事件循环,创建交互式窗口并显示其中的所有当前图形.如果您的数字超出当前在pyplot状态下实际显示的数字,则可以在调用plt.show()
之前关闭所有不需要的数字.
plt.show
starts an event loop, creates interactive windows and shows all current figures in them. If you have more figures than you actually want to show in your current pyplot state, you may close all unneeded figures prior to calling plt.show()
.
fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot([1,3,4])
fig2 = plt.figure()
ax2 = fig2.add_subplot(1, 1, 1)
ax2.plot([1,2,5])
# close first figure
plt.close(fig1)
# show all active figures (which is now only fig2)
plt.show()
相反,fig.show()
不会启动事件循环.因此,仅在事件循环已经开始的情况下才有意义,例如调用plt.show()
之后.在非交互模式下,事件循环中的事件可能发生.举个例子,当fig1处于活动状态时,只要按下键盘上的一个键,以下内容就会显示fig2
.
In contrast fig.show()
will not start an event loop. It will hence only make sense in case an event loop already has been started, e.g. after plt.show()
has been called. In non-interactive mode that may happen upon events in the event loop. To give an example, the following would show fig2
once a key on the keyboard is pressed when fig1 is active.
import matplotlib.pyplot as plt
fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot([1,3,4])
def show_new_figure(evt=None):
fig2 = plt.figure()
ax2 = fig2.add_subplot(1, 1, 1)
ax2.plot([1,2,5])
fig2.show()
# Upon pressing any key in fig1, show fig2.
fig1.canvas.mpl_connect("key_press_event", show_new_figure)
plt.show()
这篇关于不交互执行时,plt.figure.Figure.show()不执行任何操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!