Skip to main content
 首页 » 编程设计

后台 Python Matplotlib 更新图

2024年11月24日8落叶

我正在使用 Matplotlib 在 Anaconda 提示符中绘制实时事件。
当我通过 plt.draw() 或 plt.show() 更新绘图时,我失去了对我正在做的事情的控制。绘图窗口就像它被点击一样,这会阻止我在命令提示符下的其他控件。

我尝试添加

plt.show(block=False) 

但这并没有帮助。

代码如下,

fig, ax = plt.subplots() 
plt.ion() 
plt.show(block=False) 
while(True): 
    ax.plot(y_plt_points,x_plt_points,'ro') 
    plt.draw() 
    plt.pause(0.01) 

请您参考如下方法:

这link有一个使用 matplotlib 进行实时绘图的示例。我认为主要的收获是您不需要在每次调用 plot 时都使用 plt.show() 或 plt.draw() 。该示例改为使用 set_ydata。 Simalarly set_xdata 可用于更新您的 x_axis 变量。代码如下

import matplotlib.pyplot as plt 
import numpy as np 
 
# use ggplot style for more sophisticated visuals 
plt.style.use('ggplot') 
 
def live_plotter(x_vec,y1_data,line1,identifier='',pause_time=0.1): 
    if line1==[]: 
        # this is the call to matplotlib that allows dynamic plotting 
        plt.ion() 
        fig = plt.figure(figsize=(13,6)) 
        ax = fig.add_subplot(111) 
        # create a variable for the line so we can later update it 
        line1, = ax.plot(x_vec,y1_data,'-o',alpha=0.8)         
        #update plot label/title 
        plt.ylabel('Y Label') 
        plt.title('Title: {}'.format(identifier)) 
        plt.show() 
 
    # after the figure, axis, and line are created, we only need to update the y-data 
    line1.set_ydata(y1_data) 
    # adjust limits if new data goes beyond bounds 
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]: 
    plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)]) 
# this pauses the data so the figure/axis can catch up - the amount of pause can be altered above 
plt.pause(pause_time) 
 
# return line so we can update it again in the next iteration 
return line1 

当我在下面的例子中运行这个函数时,我在我的电脑上使用其他应用程序没有任何问题

size = 100 
x_vec = np.linspace(0,1,size+1)[0:-1] 
y_vec = np.random.randn(len(x_vec)) 
line1 = [] 
i=0 
while i<1000: 
    i=+1 
    rand_val = np.random.randn(1) 
    y_vec[-1] = rand_val 
    line1 = live_plotter(x_vec,y_vec,line1) 
    y_vec = np.append(y_vec[1:],0.0)