Skip to main content
 首页 » 编程设计

python之在 gui 中更新 matplotlib 图的有效方法

2025年02月15日26Free-Thinker

我的应用程序正在以大约 30fps 的速度通过网络接收数据,并且需要根据此新数据动态更新水平条形图。

为此,我在 tkinter 窗口中使用了一个 matplotlib 图。分析我的代码表明我的代码中的一个主要瓶颈是这个数字的更新。

代码的简化版本如下:

    def update_bars(self): 
        """ 
        Updates a horizontal bar chart 
        """ 
        for bar, new_d in zip(self.bars, self.latest_data): 
            bar.set_width(new_d) 
        self.figure.draw() 

我遇到的延迟很明显,并且随着时间的推移会迅速增长。有没有更有效的方法来更新 matplotlib 图?任何帮助都会很棒。

编辑:我会查看 this可能的加速技巧。如果我有一些工作,我会更新。

请您参考如下方法:

您可以更新绘图对象的数据。但在某种程度上,您无法更改绘图的形状,您可以手动重置 x 和 y 轴限制。

例如

import matplotlib.pyplot as plt 
import numpy as np 
 
x = np.linspace(0, 6*np.pi, 100) 
y = np.sin(x) 
plt.ion() 
fig = plt.figure() 
ax = fig.add_subplot(111) 
line1, = ax.plot(x, y) 
 
for phase in np.linspace(0, 10*np.pi, 500): 
    line1.set_ydata(np.sin(x + phase)) 
    # render the figure 
    # re-draw itself the next time  
    # some GUI backends add this to the GUI frameworks event loop. 
    fig.canvas.draw()  
    fig.canvas.flush_events() # flush the GUI events 

flush_events

Flush the GUI events for the figure. Implemented only for backends with GUIs.

flush_events 确保 GUI 框架有机会运行其事件循环并清除任何 GUI 事件。有时这需要在 try/except block 中,因为此方法的默认实现是引发 NotImplementedError。

draw 会渲染图形,在上面的代码中,也许删除 draw 仍然有效。但在某种程度上它们是不同的。