【问题标题】:Dynamically updating Matplotlib动态更新 Matplotlib
【发布时间】:2021-11-10 03:32:20
【问题描述】:

我想用我的笔记本中的每个时间步更新一个 Matplotlib 图形。我在 StackOverflow 上引用了许多 API resourcesexamples 论坛答案,但是,所有建议的代码要么 did not graph 要么在每个时间步显示一个新数字,如 this answer

import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np

# simulates input from serial port
def random_gen():
    while True:
        val = random.randint(1,10)
        yield val
        time.sleep(0.1)


a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()

line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()

for i in range(0,20):
    a1.appendleft(next(d))
    datatoplot = a1.pop()
    line.set_ydata(a1)
    plt.draw()
    print a1[0]
    i += 1
    time.sleep(0.1)
    plt.pause(0.0001)                       #add this it will be OK.

this answer

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.1)

如何在 Python 中通过 Matplotlib 或可能的其他方式更新每个时间步长的图形?我很欣赏你的观点。

谢谢你:)

【问题讨论】:

    标签: python matplotlib plot dynamic


    【解决方案1】:

    通过进入matplotlib的交互模式进行实时绘图。 如果只使用 plt.show() 进行绘制,程序将停止执行后续程序,所以通过 plt.ion() 打开绘图窗口进入交互模式,使用程序 plt.plot() 进行实际绘制时间,绘制完成后,使用 plt.ioff() 退出交互模式,使用 plt.show() 显示最终的图像数据。如果最后没有添加plt.show(),会闪退。

    import matplotlib.pyplot as plt
    import numpy as np
    
    ax=[]  
    ay=[]
    bx=[]   
    by=[]
    num=0  
    plt.ion()    
    # plt.rcParams['savefig.dpi'] = 200 
    # plt.rcParams['figure.dpi'] = 200 
    plt.rcParams['figure.figsize'] = (10, 10)        
    plt.rcParams['font.sans-serif']=['SimHei']   
    plt.rcParams['axes.unicode_minus'] = False
    plt.rcParams['lines.linewidth'] = 0.5   
    while num<100:
        plt.clf()    
        plt.suptitle("TITLE",fontsize=30)            
        g1=np.random.random()  
        
        ax.append(num)      
        ay.append(g1)       
        agraphic=plt.subplot(2,1,1)
        agraphic.set_title('TABLE1')      
        agraphic.set_xlabel('x',fontsize=10)   
        agraphic.set_ylabel('y', fontsize=20)
        plt.plot(ax,ay,'g-')                
        #table2
        bx.append(num)
        by.append(g1)
        bgraghic=plt.subplot(2, 1, 2)
        bgraghic.set_title('TABLE2')
        bgraghic.plot(bx,by,'r^')
    
        plt.pause(0.4)     
        if num == 15:
            plt.savefig('picture.png', dpi=300) 
            #break
        num=num+1
    
    plt.ioff()       
    plt.show()       
    

    【讨论】:

    • 我在笔记本中复制并执行了您的代码。结果生成了 TABLE1 和 TABLE2 的 100 个图形,而不是各自图形的 100 个更新。这在我的 Github 存储库中this Notebook 的“头脑风暴”单元格中呈现。是我的笔记本设置错误吗?谢谢你:)
    猜你喜欢
    • 2020-12-28
    • 2022-01-25
    • 2012-06-12
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多