如何使matplotlib(python)窗口保持在后台?

2024-04-20 07:13:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python/matplotlib应用程序,它经常用来自测量仪器的新数据更新绘图。当绘图用新数据更新时,相对于桌面上的其他窗口,绘图窗口不应从背景更改为前景(反之亦然)。在

在运行Ubuntu16.10和matplotlib 1.5.2rc的机器上,python3可以正常工作。但是,在另一台装有ubuntu17.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)

Tags: 数据fromimport机器绘图timeplotmatplotlib
1条回答
网友
1楼 · 发布于 2024-04-20 07:13:25

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

相关问题 更多 >