【发布时间】:2016-02-24 12:59:53
【问题描述】:
所以我有一些 python 代码可以使用 pyplot 绘制一些图形。每次我运行脚本时,都会创建新的绘图窗口,我必须手动关闭。如何在脚本开始时关闭所有打开的 pyplot 窗口? IE。关闭在之前执行脚本期间打开的窗口?
在 MatLab 中,这可以简单地通过使用 closeall 来完成。
【问题讨论】:
标签: python matplotlib pycharm
所以我有一些 python 代码可以使用 pyplot 绘制一些图形。每次我运行脚本时,都会创建新的绘图窗口,我必须手动关闭。如何在脚本开始时关闭所有打开的 pyplot 窗口? IE。关闭在之前执行脚本期间打开的窗口?
在 MatLab 中,这可以简单地通过使用 closeall 来完成。
【问题讨论】:
标签: python matplotlib pycharm
要关闭脚本中所有打开的图形,您可以调用
plt.close('all')
或者您可以终止关联的 Python 进程。
【讨论】:
import matplotlib.pyplot as plt
plt.close("all")
(如果你已经导入了 pyplot,你显然不需要再次导入它。在这种情况下,只需确保将 plt.close("all") 中的 plt 替换为导入时为 pyplot 选择的任何别名。 )
【讨论】:
此解决方案不允许您关闭以前运行的图,但会阻止您将它们保持打开状态!
我发现关闭这些“挂起”数字的唯一方法是找到进程并杀死。
以非阻塞方式绘图,然后请求输入。这应该可以防止您忘记正确关闭情节。
plt.show(block=False)
plt.pause(0.001) # Pause for interval seconds.
input("hit[enter] to end.")
plt.close('all') # all open plots are correctly closed after each run
【讨论】:
我也遇到了同样的问题。我调用一个生成多个绘图窗口的函数。每次我调用该函数时,弹出的绘图窗口都会累积数量。在函数开头尝试matplotlib.pyplot.close('All') 并没有解决问题。我通过调用matplotlib.pyplot.close(figure) 解决了这个问题,其中 figure 是绘图图实例(对象)。
我维护了一个我的绘图对象列表。因此,最好维护一个列表,然后为图形对象的每个实例调用matplotlib.pyplot.close(figure):
import matplotlib.pyplot as plot
fig, (ax1,ax2) = plt.subplots(nrows=2)
figAxisDict = {'figure': fig, 'axis1': ax1, 'axis2':ax2}
figAxisList.append(figAxisDict)
if len(figAxisList) !=0:
for figAxis in figAxisList:
figure=figAxis['figure']
plot.close(figure)
figAxisList[:]=[]
【讨论】:
由于似乎没有绝对简单的解决方案可以从脚本本身自动执行此操作:关闭 pycharm 中所有现有数字的可能最简单的方法是杀死相应的进程(正如 jakevdp 在他的评论中建议的那样):
菜单运行\停止... (Ctrl-F2)。您会发现窗口关闭后延迟了几秒钟。
【讨论】:
老实说,开发人员需要像在 MATLAB 中一样将其作为一个简单的函数。
我对 Spyder 的临时解决方案:
这些坐标是您需要在下面的代码中替换的坐标。
import keyboard
from pynput.mouse import Button, Controller
#%% Clear Old Plots
#Selects the mouse as the controller
mouse = Controller()
#Record current mouse position
recmp = mouse.position
#Set pointer position on plots pane
mouse.position = (1136,370) # <-- replace coordinates here with yours!
#Opens the plot pane
keyboard.press_and_release('ctrl+shift+g')
#Click and release left mouse button
mouse.press(Button.left)
mouse.release(Button.left)
#Runs close all in the plots pane
keyboard.press_and_release('ctrl+shift+w')
#Resets mouse position to the original location
mouse.position = recmp
【讨论】:
在 *nix 上你可以使用killall 命令。
killall app
使用窗口名称的 app 关闭每个窗口实例。
您还可以在 Python 脚本中使用相同的命令。
您可以使用os.system("bashcommand") 来运行 bash 命令。
【讨论】: