【问题标题】:Real time plotting in matplotlib from a numpy array从 numpy 数组在 matplotlib 中实时绘图
【发布时间】:2021-08-22 04:19:21
【问题描述】:

我的任务是使用 ma​​tplotlib 实时绘制 numpy 数组。请注意,我不想使用 animation 函数来执行此操作。

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

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

【问题讨论】:

  • 使用line.set_data(xs, ys)fig.canvas.draw()在用line, = self.axis.plot(xs, ys, 'g-')初始化后更新图形

标签: python python-3.x numpy matplotlib


【解决方案1】:
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

关于上述函数的几点说明:

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

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

用户将需要返回 line1 来控制该行,因为它被更新并发送回函数

用户还可以自定义功能,允许标题、x-label、y-label、x-limits等动态变化。

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 2019-06-30
    • 2018-08-30
    • 2021-06-16
    • 2011-02-11
    • 2018-11-09
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多