繁体   English   中英

从 numpy 阵列中的 matplotlib 实时绘图

[英]Real time plotting in matplotlib from a numpy array

我的任务是使用matplotlib实时 plot 一个numpy数组。 请注意,我不想使用animation function 来执行此操作。

import numpy as np
import  time 
from matplotlib.lines import Line2D
import matplotlib

class Plot:
    def __init__(self,f,axis,data):
        self.fig = f
        self.axis = axis
        self.data = data 
        
    def plotting(self,i):
        xs = [self.data[i,0],self.data[i+1,0]]
        ys = [self.data[i,1],self.data[i+1,1]]
        line, = self.axis.plot(xs,ys,'g-')
        
        self.fig.canvas.draw()
        
data = np.random.rand(10,2) #numpy array
f = plt.figure()
axis = f.add_axes([0,0,0.9,0.9])    
        
plotData = Plot(f,axis,data)
for i in range(len(data)-1):
    plotData.plotting(i)
    time.sleep(1)

plt.show()

但每次我运行这段代码时,它都会返回一个空图。 我该如何纠正它?

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

关于上面function的几点说明:

line1.set_ydata(y1_data) 也可以切换到 line1.set_data(x_vec,y1_data) 以更改绘图上的 x 和 y 数据。

plt.pause() 是让绘图仪赶上所必需的 - 我已经能够使用 0.01s 的暂停时间而没有任何问题

用户需要返回 line1 以控制线路,因为线路已更新并发送回 function

用户还可以自定义 function 以允许动态更改标题、x-label、y-label、x-limits 等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM