python - 非阻塞 Matplotlib 动画

标签 python matplotlib

我想在我的主程序中同时运行 FuncAnimation,不幸的是,它阻止了 MainProgram 的执行。无论我做什么。
我试过了:

  • plt.show(block=False)程序继续,但绘图显示空白
  • 返回动画并存储在变量中 - MainProgram被阻止
  • 两者:MainProgram运行但绘图窗口为空白

  • 我知道这个问题,但是,我认为考虑到动画的使用,提出的解决方案是不合适的。
    Plotting in a non-blocking way with Matplotlib
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    import numpy as np
    import time
    
    def runGraph():
        # Parameters
        x_len = 200         # Number of points to display
        y_range = [10, 40]  # Range of possible Y values to display
    
        # Create figure for plotting
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        xs = list(range(0, 200))
        ys = [0] * x_len
        ax.set_ylim(y_range)
    
        # Create a blank line. We will update the line in animate
        line, = ax.plot(xs, ys)
    
        # Add labels
        plt.title('TMP102 Temperature over Time')
        plt.xlabel('Samples')
        plt.ylabel('Temperature (deg C)')
    
        # This function is called periodically from FuncAnimation
        def animate(i, ys):
    
            # Read temperature (Celsius) from TMP102
            temp_c = np.random.random(1)*40
    
            # Add y to list
            ys.append(temp_c)
    
            # Limit y list to set number of items
            ys = ys[-x_len:]
    
            # Update line with new Y values
            line.set_ydata(ys)
    
            return line,
    
        # Set up plot to call animate() function periodically
        ani = animation.FuncAnimation(fig,
            animate,
            fargs=(ys,),
            interval=50,
            blit=True)
        plt.show()
    
    def MainProgram():
         while 1:
             print('Main program')
             time.sleep(0.5)
    
    if __name__ == '__main__':
        runGraph()
        MainProgram()
    

    最佳答案

    解决此问题的最通用方法是使用 multiprocessing模块。

    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    from multiprocessing import Process
    import numpy as np
    import time
    
    def runGraph():
        # Parameters
        print('show')
        x_len = 200         # Number of points to display
        y_range = [10, 40]  # Range of possible Y values to display
    
        # Create figure for plotting
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        xs = list(range(0, 200))
        ys = [0] * x_len
        ax.set_ylim(y_range)
    
        # Create a blank line. We will update the line in animate
        line, = ax.plot(xs, ys)
    
        # Add labels
        plt.title('TMP102 Temperature over Time')
        plt.xlabel('Samples')
        plt.ylabel('Temperature (deg C)')
    
        # This function is called periodically from FuncAnimation
        def animate(i, ys):
    
            # Read temperature (Celsius) from TMP102
            temp_c = np.random.random(1)*40
    
            # Add y to list
            ys.append(temp_c)
    
            # Limit y list to set number of items
            ys = ys[-x_len:]
    
            # Update line with new Y values
            line.set_ydata(ys)
    
            return line,
    
    
        # Set up plot to call animate() function periodically
    
        ani = animation.FuncAnimation(fig,
            animate,
            fargs=(ys,),
            interval=50,
            blit=True)
        plt.show()
    
    
    
    def MainProgram():
         while 1:
             print('Main program')
             time.sleep(0.5)
    
    if __name__ == '__main__':
        p = Process(target=runGraph)
        p.start()
        MainProgram()
        p.join()
    

    关于python - 非阻塞 Matplotlib 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51949185/

    相关文章:

    python - Python 中的属性解析如何工作?

    python - 在 cython : defining ndarray datatype/ndims 中使用 numpy

    python - python中的行结尾

    python - 如何使用 matplotlib 绘制 .txt 文件中的数据

    python - 在 Python3 中使用 NetworkX 创建弯曲边缘

    python - python 函数生成源的 SCons 和依赖项

    python - 根据索引值和条件语句将行值相加

    python - 更改matplotlib中zoom-rect的边缘颜色

    python - 每个子图中的 matplotlib 颜色条

    python - 如何在 python 上绘制颜色条