简体   繁体   中英

Real time plotting in matplotlib from a numpy array

My task is to plot a numpy array in real time using matplotlib . Please note that I don't want to use animation function to do this.

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()

But everytime I run this code it returns me one empty figure. How do I rectify it?

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

A few notes on the function above:

line1.set_ydata(y1_data) can also be switched to line1.set_data(x_vec,y1_data) to change both x and y data on the plots.

plt.pause() is necessary to allow the plotter to catch up - I've been able to use a pause time of 0.01s without any issues

The user will need to return line1 to control the line as it is updated and sent back to the function

The user can also customize the function to allow dynamic changes of title, x-label, y-label, x-limits, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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