2017-05-31 295 views
3

我有一個python/matplotlib應用程序,它經常用來自測量儀器的新數據更新圖表。當繪圖更新爲新數據時,對於桌面上的其他窗口,繪圖窗口不應從背景變爲前景(反之亦然)。如何在後臺保持matplotlib(python)窗口?

在運行Ubuntu 16.10和matplotlib 1.5.2rc的機器上,它可以像Python 3那樣工作。但是,在使用Ubuntu 17.04和matplotlib 2.0.0的另一臺計算機上,每當使用新數據更新繪圖時,數字窗口都會彈出到前端。

如何在使用新數據更新繪圖時控制窗口前景/背景行爲並保持窗口焦點?

這裏是我的說明繪製程序的代碼示例:

import matplotlib 
import matplotlib.pyplot as plt 
from time import time 
from random import random 

print (matplotlib.__version__) 

# set up the figure 
fig = plt.figure() 
plt.xlabel('Time') 
plt.ylabel('Value') 
plt.ion() 

# plot things while new data is generated: 
t0 = time() 
t = [] 
y = [] 
while True: 
    t.append(time()-t0) 
    y.append(random()) 
    fig.clear() 
    plt.plot(t , y) 
    plt.pause(1) 
+0

正如我不能以任何方式進行測試,只是一個建議嘗試什麼:不是'plt.ion()',如果你使用'plt.show(塊= FALSE)',然後會發生什麼你的'while'循環在'plt.plot()'調用之後加上'plt.draw()'? –

+0

@ThomasKühn:謝謝你的建議。但是,這並沒有改變Ubuntu 17.04/matplotlib 2.0.0環境中的任何內容。 – mbrennwa

+0

您使用的是什麼[後端](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend)?這可能是值得改變的,看看這是否能解決問題。 –

回答

0

matplotlib從版本1.5.2rc地方改爲2.0.0這樣pyplot.show()將窗口前臺(見here) 。因此,關鍵是避免在循環中調用pyplot.show()pyplot.pause()也是如此。

下面是一個工作示例。這仍然會在一開始就把窗口帶到前臺。但是用戶可能會將窗口移動到後臺,並且在用新數據更新數字時窗口將停留在那裏。

請注意,matplotlib動畫模塊可能是生成此示例中顯示的圖的理想選擇。但是,我無法通過交互式繪圖使動畫工作,因此它阻止了其他代碼的進一步執行。這就是爲什麼我不能在我的真實應用程序中使用動畫模塊。

import matplotlib 
matplotlib.use('TkAgg') 
import matplotlib.pyplot as plt 
import time 
from random import random 

print (matplotlib.__version__) 

# set up the figure 
plt.ion() 
fig = plt.figure() 
ax = plt.subplot(1,1,1) 
ax.set_xlabel('Time') 
ax.set_ylabel('Value') 
t = [] 
y = [] 
ax.plot(t , y , 'ko-' , markersize = 10) # add an empty line to the plot 
fig.show() # show the window (figure will be in foreground, but the user may move it to background) 

# plot things while new data is generated: 
# (avoid calling plt.show() and plt.pause() to prevent window popping to foreground) 
t0 = time.time() 
while True: 
    t.append(time.time()-t0) # add new x data value 
    y.append(random())  # add new y data value 
    ax.lines[0].set_data(t,y) # set plot data 
    ax.relim()     # recompute the data limits 
    ax.autoscale_view()   # automatic axis scaling 
    fig.canvas.flush_events() # update the plot and take care of window events (like resizing etc.) 
    time.sleep(1)    # wait for next loop iteration 
+0

如果你有使用'time.sleep'的UI問題,就像無法移動/調整窗口大小一樣,看看這個答案https: //stackoverflow.com/a/45734500/277267這是'plt.pause'方法的重新實現。 –