【问题标题】:Efficient way to update matplotlib figure in gui?在 gui 中更新 matplotlib 图形的有效方法?
【发布时间】:2017-08-09 20:58:52
【问题描述】:

我的应用程序正在以大约 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 以获取可能的加速提示。如果我得到一些工作,我会更新。

【问题讨论】:

标签: python matplotlib tkinter


【解决方案1】:

您可以更新绘图对象的数据。但在某种程度上,你不能改变绘图的形状,你可以手动重置 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

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

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

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

【讨论】:

  • 我会尝试你的建议,谢谢顺便说一句。不过我很好奇,我看到了对 draw() 的调用,之后调用 flush_events() 不是多余的吗? (我对 GUI 开发不太熟悉,所以如果我的问题似乎无知,请原谅我) 编辑:我只是尝试了你的建议,似乎没有任何区别:(
猜你喜欢
  • 2015-08-26
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多