2020-09-22

Original animation drawing
1. In the process of drawing graphics and images, you can use the control of drawing time to gradually display the drawing content, and then achieve
the effect of dynamic display of graphics and images.
Use plot() and scatter() to draw sine waves and scatter plots. The scatter plot is drawn dynamically along a sine wave. The implementation code is as follows (my test environment is IDIE, if it is in the Jupyter Notebook environment, the effect is not very obvious)

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0,2*np.pi,300)    #正弦x轴上一个周期360度的弧度值
y = np.sin(3*x)+5   #一个周期内振荡频率为3,在y轴上向上移动5
plt.plot(x,y,color='r')   #绘制正弦波图形
x1 = x[::2]
y1 = y[::2]
i = 0
for pos in x1:  #弹出一个x轴值,然后获取对应的y轴值,绘制散点图
    ax.scatter(pos,y1[i],c='b',marker='.')   #按照正弦波方向绘制散点图
    i += 1
    plt.pause(0.008)    #循环一次暂停0.008秒一下
plt.show()

If you are in the Jupyter Notebook environment, you need to add the following two lines of code at the beginning:

%matplotlib notebook
from IPython import display

Insert picture description here
2. The draw() method
plt.draw() can redraw the corresponding new graphics in the data area according to the new data provided.
To change, you need to change the x, y coordinate range of the original graph through the ax.set_xdata(x), ax.set_ydata(y) attached to the instance ax returned by the drawing tools like plt.plot(), plt.scatter() To achieve the purpose of changing the graphics. As for the animation effect, through the control of the time interval, plt.draw can redraw the frames regularly and repeatedly to realize the dynamic replacement of the frames.
1) Simple redrawing setting
Here, the plt.draw() function is used to dynamically redraw according to the changes of the x and y coordinates of the plt.plot() drawing tool. code show as below

import numpy as np
import math
import matplotlib.pyplot as plt
from time import sleep  
plt.subplots()
xMax = 500
x = np.linspace(0,2*np.pi,xMax)
y = np.sin(x)
plt.plot(x,y,'b--')    #设置轨迹虚线
sleep(0.5)
ax,= plt.plot(x,y,'ro')   
i = 0
while i <= xMax:
    plt.pause(0.002)    #暂停0.002秒,功能同sleep()
    y1 = np.sin(x[:i])   #这里采用逐步增加y轴值范围的方法
    ax.set_xdata(x[:i])   #这里采用逐步增加x轴值范围的方法
    ax.set_ydata(y1)
    plt.draw()     #重画已经修改的图形
    i += 2      #获取范围控制,兼循环控制
plt.show()

Insert picture description here
2. With buttons to control the animation. The
following code uses the draw() method to redraw the graphics given the value. In essence, it also controls the drawing progress through sleep() to achieve the effect of dynamic drawing.

import numpy as np
from threading import Thread          
import math
import matplotlib.pyplot as plt
from time import sleep  
from matplotlib.widgets import Button     #导入按钮对象
fig,ax = plt.subplots()
#实验数据
x = np.arange(0,1,0.001)
y = np.sin(4*np.pi*x)*np.exp(-x) 
ax, = plt.plot(x,y,lw=1,marker='D',color='c')
class ButtonHandler:              #自定义按钮事件类,封装了单击事件的开始方法和停止方法
    def __init__(self):
        self.flag = True        #是否启动线程,动态处理绘制过程
        self.x_s,self.x_e,self.x_step = 0,1,0.01
    def threadStart(self):       #线程开始函数,用来更新数据并重新绘制图形
        while self.flag:
            sleep(0.02)
            self.x_s += self.x_step     #开始位置一次加0.01
            self.x_e += self.x_step    #结束位置一次加0.01
            x1 = np.arange(self.x_s,self.x_e,self.x_step)   
            y1 = np.sin(4*np.pi*x1)*np.exp(-x1)     #输出y轴范围值
            ax.set_xdata(x1-x1[0])      #重新绘制新绘制区域x,y数据
            ax.set_ydata(y1)
            plt.draw()                 #重新绘制图形
    def Start(self,event):
        self.flag = True
        t1 = Thread(target=self.threadStart)        #创建并启动线程
        t1.start()
    def Stop(self,event):
        self.flag = False
callback = ButtonHandler()
#利用两个新的axes区域,创建按钮并设置单击事件处理函数
y1 = 0.8
ax1 = plt.axes([0.81,0.05+y1,0.1,0.075])
bs = Button(ax1,'Stop',color='m')
bs.on_clicked(callback.Stop)
ax2 = plt.axes([0.7,0.05+y1,0.1,0.075])
bp = Button(ax2,'Start',color='y')
bp.on_clicked(callback.Start)
plt.show()

Insert picture description here

Guess you like

Origin blog.csdn.net/changshupx/article/details/108730160