【问题标题】:Dynamically updating plot in matplotlib在 matplotlib 中动态更新绘图
【发布时间】:2012-06-12 06:19:35
【问题描述】:

我正在用 Python 制作一个应用程序,它从串行端口收集数据并绘制收集到的数据与到达时间的关系图。数据到达的时间是不确定的。我希望在收到数据时更新绘图。我搜索了如何做到这一点,发现了两种方法:

  1. 清除绘图并重新绘制所有点的绘图。
  2. 通过在特定时间间隔后更改情节来制作动画。

我不喜欢第一个,因为程序运行并收集数据很长时间(例如一天),重绘情节会很慢。 第二个也不可取,因为数据的到达时间不确定,我希望图仅在收到数据时更新。

有没有一种方法可以让我只在收到数据时才添加更多点来更新绘图?

【问题讨论】:

标签: python matplotlib tkinter


【解决方案1】:

有没有一种方法可以通过添加更多点来更新情节...

matplotlib 中有多种动画数据的方法,具体取决于您拥有的版本。你见过matplotlib cookbook 的例子吗?另外,请查看 matplotlib 文档中更现代的 animation examples。最后,animation API 定义了一个函数FuncAnimation,它可以及时为函数设置动画。此函数可能只是您用来获取数据的函数。

每个方法基本上都设置了正在绘制的对象的data属性,因此不需要清除屏幕或图形。 data 属性可以简单地扩展,因此您可以保留之前的点并继续添加到您的线条(或图像或您正在绘制的任何内容)。

鉴于您说您的数据到达时间不确定,您最好的选择可能只是执行以下操作:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

然后当你从串口接收数据时,只需调用update_line

【讨论】:

【解决方案2】:

为了在没有 FuncAnimation 的情况下执行此操作(例如,您想在生成绘图时执行代码的其他部分,或者您想同时更新多个绘图),单独调用 draw 不会产生绘图(至少使用 qt 后端)。

以下对我有用:

import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #Need both of these in order to rescale
        self.ax.relim()
        self.ax.autoscale_view()
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def __call__(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

【讨论】:

  • 是的!终于找到了一个适用于 Spyder 的解决方案!我缺少的是在 draw() 命令之后的 gcf().canvas.flush_events()。
  • 基于这个很好的例子,我写了一个小的 Python 模块,允许重复绘图:github.com/lorenzschmid/dynplot
  • 一个很好的例子!
  • 清晰、简洁、通用、灵活:这应该是公认的答案。
  • 要在 Jupyter Notebook 中使用它,您必须在 matplotlib 导入语句后添加 %matplotlib notebook 魔术命令。
【解决方案3】:

我知道我回答这个问题迟到了,但是对于您的问题,您可以查看“游戏杆”包。我设计它是为了从串行端口绘制数据流,但它适用于任何流。它还允许交互式文本记录或图像绘图(除了图形绘图)。 无需在单独的线程中执行自己的循环,包会处理它,只需提供您希望的更新频率。此外,终端在绘图时仍可用于监控命令。 见http://www.github.com/ceyzeriat/joystick/https://pypi.python.org/pypi/joystick(使用pip install摇杆安装)

只需在下面的代码中将 np.random.random() 替换为从串口读取的真实数据点:

import joystick as jk
import numpy as np
import time

class test(jk.Joystick):
    # initialize the infinite loop decorator
    _infinite_loop = jk.deco_infinite_loop()

    def _init(self, *args, **kwargs):
        """
        Function called at initialization, see the doc
        """
        self._t0 = time.time()  # initialize time
        self.xdata = np.array([self._t0])  # time x-axis
        self.ydata = np.array([0.0])  # fake data y-axis
        # create a graph frame
        self.mygraph = self.add_frame(jk.Graph(name="test", size=(500, 500), pos=(50, 50), fmt="go-", xnpts=10000, xnptsmax=10000, xylim=(None, None, 0, 1)))

    @_infinite_loop(wait_time=0.2)
    def _generate_data(self):  # function looped every 0.2 second to read or produce data
        """
        Loop starting with the simulation start, getting data and
    pushing it to the graph every 0.2 seconds
        """
        # concatenate data on the time x-axis
        self.xdata = jk.core.add_datapoint(self.xdata, time.time(), xnptsmax=self.mygraph.xnptsmax)
        # concatenate data on the fake data y-axis
        self.ydata = jk.core.add_datapoint(self.ydata, np.random.random(), xnptsmax=self.mygraph.xnptsmax)
        self.mygraph.set_xydata(t, self.ydata)

t = test()
t.start()
t.stop()

【讨论】:

    【解决方案4】:

    这是一种允许在绘制一定数量的点后删除点的方法:

    import matplotlib.pyplot as plt
    # generate axes object
    ax = plt.axes()
    
    # set limits
    plt.xlim(0,10) 
    plt.ylim(0,10)
    
    for i in range(10):        
         # add something to axes    
         ax.scatter([i], [i]) 
         ax.plot([i], [i+1], 'rx')
    
         # draw the plot
         plt.draw() 
         plt.pause(0.01) #is necessary for the plot to update for some reason
    
         # start removing points if you don't want all shown
         if i>2:
             ax.lines[0].remove()
             ax.collections[0].remove()
    

    【讨论】:

    • plt.pause(0.01) 是我需要的。谢谢!!
    猜你喜欢
    • 2020-11-06
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多