Note

Go to the endto download the full example code.

Oscilloscope#

Emulates an oscilloscope.

Output generated viamatplotlib.animation.Animation.to_jshtml.

importmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlib.animationasanimationfrommatplotlib.linesimportLine2DclassScope:def__init__(self,ax,maxt=2,dt=0.02):self.ax=axself.dt=dtself.maxt=maxtself.tdata=[0]self.ydata=[0]self.line=Line2D(self.tdata,self.ydata)self.ax.add_line(self.line)self.ax.set_ylim(-.1,1.1)self.ax.set_xlim(0,self.maxt)defupdate(self,y):lastt=self.tdata[-1]iflastt>=self.tdata[0]+self.maxt:# reset the arraysself.tdata=[self.tdata[-1]]self.ydata=[self.ydata[-1]]self.ax.set_xlim(self.tdata[0],self.tdata[0]+self.maxt)self.ax.figure.canvas.draw()# This slightly more complex calculation avoids floating-point issues# from just repeatedly adding `self.dt` to the previous value.t=self.tdata[0]+len(self.tdata)*self.dtself.tdata.append(t)self.ydata.append(y)self.line.set_data(self.tdata,self.ydata)returnself.line,defemitter(p=0.1):"""Return a random value in [0, 1) with probability p, else 0."""whileTrue:v=np.random.rand()ifv>p:yield0.else:yieldnp.random.rand()# Fixing random state for reproducibilitynp.random.seed(19680801//10)fig,ax=plt.subplots()scope=Scope(ax)# pass a generator in "emitter" to produce data for the update funcani=animation.FuncAnimation(fig,scope.update,emitter,interval=50,blit=True,save_count=100)plt.show()# ..tags:: animation, plot-type: line

Total running time of the script: (0 minutes 9.480 seconds)

Gallery generated by Sphinx-Gallery