在 gui 中更新 matplotlib 图的有效方法? [英] Efficient way to update matplotlib figure in gui?

查看:53
本文介绍了在 gui 中更新 matplotlib 图的有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My application is receiving data over the network at about 30fps, and needs to update a horizontal bar chart dynamically based on this new data.

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

I am using a matplotlib figure inside a tkinter window for this purpose. Profiling my code has shown that a major bottleneck in my code is the updating of this figure.

下面是代码的简化版本:

A simplified version of the code is given below:

    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 图?任何帮助都会很棒.

The lag I am experiencing is significant, and grows quickly over time. Is there a more efficient way to update the matplotlib figure? Any help would be great.

我将在可能的加速技巧.如果有什么事情我会更新.

I will be looking at this for possible speedup tips. I'll update if I get something working.

推荐答案

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

You can update the data of the plot objects. But to some extent, you can't change the shape of the plot, you can manually reset the x and y axis limits.

例如

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

刷新图形的 GUI 事件.仅针对后端实施带有图形用户界面.

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

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

flush_events make sure that the GUI framework has a chance to run its event loop and clear any GUI events.Sometimes this needs to be in a try/except block because the default implementation of this method is to raise NotImplementedError.

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

draw will render the figure,in the above code,maybe remove draw still work.But to some extent they're different.

这篇关于在 gui 中更新 matplotlib 图的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆