2 回答

TA貢獻1795條經驗 獲得超7個贊
也許以下是您正在尋找的內容。由于這個問題真的很廣泛,同時要求很多東西,我將把它限制在前兩個例子中。這里的關鍵是使用plt.ion().
import matplotlib
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt
X=[0,1]
Y=[0,1]
Y2a=[0,2]
Y2b=[0,2.5]
Y3a=[0,3]
Y3b=[0,3.5]
Y4=[0,4]
plt.ion()
fig, ax = plt.subplots() # Nothing happens
ax.plot(X,Y) # Nothing happens
plt.draw()
plt.pause(.1) # New window (1) appears and shows plot of X,Y; execution continues directly
ax.set_xlabel('X') # Window 1 gets X axis label
ax.set_ylabel('Y') # Window 1 gets Y axis label
figManager = plt.get_current_fig_manager()
figManager.window.showMinimized() # Window 1 disappears
plt.pause(10) # No open windows for 10 seconds
figManager.window.showNormal() # Window 1 reappears and looks the same as before
fig2 = plt.figure() # Nothing happens
fig2.show() # New window (2) appears and is empty
ax2 = fig2.gca() # Window 2 shows axes
ax2.plot(X,Y2a) # Window 2 shows X,Y2a
pass # Nothing happens, could be omitted
for i in range(60*2):
plt.pause(1/2) # Long computation. In the meantime, windows 1 and 2 can still be resized and their controls (zoom etc.) can be used
ax2.plot(X,Y2b) # Window 2 shows X,Y2a as well as X,Y2b
figManager = plt.get_current_fig_manager()
figManager.window.showMinimized() # Window 2 disappears
(1) plt.ion 在這里做什么?
plt.ion()打開交互模式。這意味著可以在 GUI 內繪制圖形而無需啟動 GUI 事件循環。優點很明顯,GUI事件循環不會阻塞后續代碼;缺點是您沒有事件循環 - 因此 GUI 可能很快變得無響應,您需要自行負責讓它管理事件。這就是plt.pause在這種情況下的作用??赡馨l生的情況是,無論您使用什么來運行腳本,都已經為您打開了交互模式。在這種情況下plt.ioff(),請使用以查看差異。
(2) 可以在不抓住焦點的情況下實現像 plt.pause 這樣的東西嗎?
可能,但大多數用戶希望在繪制時實際看到他們的圖。所以它不是以這種方式實現的。
(3)如果plt.draw沒有plt.pause(.1)沒有任何效果,為什么它以當前的形式存在?
plt.draw()繪制圖形。這在各種情況下都很有用,并且完全獨立于是否ion使用。
(4) fig.show 在概念上是否與 (a) 如果不存在打開窗口相同 (b) 將焦點放在窗口 (c) plt.draw();plt.pause(0.1) 上?
我對此表示強烈懷疑。然而,它可能在交互模式下具有相同的面向用戶的效果。
(5) 在進行實際計算(與 plt.pause 相反)時,真的不可能讓數字響應嗎?
不可以。您可以在事件循環內運行計算。您也可以在線程中運行它。最后,您可以在計算過程中調用plt.pause()或fig.canvas.flush_events()重復。
(6)figManager.window.showMinimized對我沒有任何影響;那是因為這是操作系統相關的嗎?
它不應該依賴于操作系統。但它肯定依賴于后端。這就是我將后端設置在代碼之上的原因。
添加回答
舉報