matplotlib绘图-斜上抛运动

matplotlib是Python中绘制2D图形使用最多的库,可以很轻松的将数据图形化。本文绘制了斜上抛运动,下面是最终的效果。


(菲菲老师教得好,幸不辱命 (•‾̑⌣‾̑•)✧˖° )

  1. 导入所需数据包
    这里的animation.FuncAnimation(fig,update,generate,interval = 5)函数,是用于生成动态图片的。其中fig表示生成的图表对象;generate函数生成数据后传递给update函数更新,这样数据不断更新,图形也不停变化;interval表示时间间隔,设置的值越小,运动速度越快

            
            
    1
    2
    3
            
            
    from matplotlib import pyplot as plt
    from matplotlib import animation
    import math
  2. 设置图形窗口参数

            
            
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
            
            
    font=FontProperties(fname= r"c:windowsfontssimsun.ttc",size= 14)
    # 初始化图形窗口
    fig = plt.figure()
    ax = fig.add_subplot( 111)
    ax.set_aspect( 'equal')
    # 设置坐标轴的x,y取值范围
    xmin = 0
    ymin = 0
    ax = plt.axes(xlim = (xmin, xmax), ylim = (ymin, ymax))
    # 创建一个圆,圆点在(0,0),半径为1
    circle = plt.Circle((xmin, ymin), 1)
    ax.add_patch(circle)
  3. 给定初始参数值

            
            
    1
    2
    3
    4
            
            
    g = 9.8
    u = 30 # 斜上抛的初速度
    theta = 60 # 与水平方向的夹角θ
    theta_radians = math.radians(theta) # 返回一个角度的弧度值
  4. 计算衍生参数

    大专栏 matplotlib绘图-斜上抛运动

    「制作动态效果」

    主要利用前面介绍的animation.FuncAnimation函数。于是我们需要构造generate与update函数,让它动起来~

    generate函数

    <  /table>
            
            
    1
    2
    3
    4
            
            
    t_flight= 2*u*math.sin(theta_radians)/g # 从A点到B点所需时间
    t_max = u*math.sin(theta_radians)/g # 上升到最大高度所需时间
    xmax = u*math.cos(theta_radians)*t_flight # AB两点的距离
    ymax = u*math.sin(theta)*t_max - 0.5*g*t_max** 2 # 上升的最大高度
            
            
    1
    2
    3
    4
    5
    6
            
            
    #产生时间间隔参数(每个数据间隔为0.05),依次传递给updata函数
    def ():
    t = 0
    while t < t_flight:
    t += 0.05
    yield t

    update函数

            
            
    1
    2
    3
    4
    5
    6
            
            
    #更新时间间隔参数,从而不断改变圆的圆心坐标位置,让其移动
    def update(t):
    x = u*math.cos(theta_radians)*t
    y = u*math.sin(theta_radians)*t - 0.5*g*t*t
    circle.center = x, y
    return circle,

    打印相关信息

            
            
    1
    2
    3
    4
    5
            
            
    def Print():
    print ( u"初始速度(米/秒):",u)
    print ( u"发射角度(度)",theta)
    print ( u"飞行总时间(秒)",t_flight)
    print ( u"飞行距离(米)",xmax)

    动画函数

            
            
    1
    2
    3
    4
    5
    6
    7
    8
    9
            
            
    anim = animation.FuncAnimation(fig, update,generate,interval= 10)
    # 附加信息
    anim= animation.FuncAnimation(fig, update,generate,interval= 10)
    plt.title( u'导弹发射轨迹',fontproperties=font)
    plt.xlabel( u'水平距离(米)',fontproperties=font)
    plt.ylabel( u'导弹运行高度(米)',fontproperties=font)
    plt.show()
    Print()

    最后就能看到首页的动态图了 ヾ(◍’౪`◍)ノ゙

猜你喜欢

转载自www.cnblogs.com/sanxiandoupi/p/11693241.html