欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Matplotlib动画(三):慢车与快车相向而行

程序员文章站 2021-12-18 16:31:56
...

本文主要使用Python和Matplotlib制作动画,动态演示初中数学中的慢车与快车相向而行的问题。

本文使用的软件:

  • Python 3.8.8
  • Matplotlib 3.3.4
  • PyCharm 2018.3.3(Community Edition)

1 题目

一辆慢车从甲地匀速行驶至乙地,一辆快车同时从乙地匀速行驶至甲地,两车之间的距离y(km)与行驶时间t(h)之间的对应关系如图所示,当两车相距300km时,x的值是多少?

Matplotlib动画(三):慢车与快车相向而行

 2 动画源代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

pointA = 0
pointB = 600
xdata, ydata = [], []
speedA = 60
speedB = 90
frame_move = np.arange(0, 10 + 0.1, 0.1)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
plt.rc('font', family='Times New Roman', size=9)

plt.title('慢车与快车相向而行', fontfamily='SimHei')
dot_a, = axes[0].plot([], [], 'bo')
dot_b, = axes[0].plot([], [], 'ro')
text_a = axes[0].text(pointA, -5, '慢车', fontfamily='KaiTi')
text_b = axes[0].text(pointB, -5, '快车', fontfamily='KaiTi')
line_distance, = axes[1].plot([], [], 'r-')
text_distance = axes[1].text(3, 500, '')


def init_graph():
    # print('init frame')
    axes[0].text(0, 20,
    '''
一辆慢车从甲地匀速行驶至乙地,一辆
快车同时从乙地匀速行驶至甲地,两车
之间的距离y(km)与行驶时间t(h)之
间的对应关系如图所示,当两车相距
300km时,x的值是多少?(@猴小萌)''', fontfamily='FangSong', fontsize=10)
    axes[0].plot([pointA, pointA, pointB, pointB], [2, 0, 0, 2], 'k-')
    axes[0].text(pointA, -5, '甲地', fontfamily='KaiTi')
    axes[0].text(pointB, -5, '乙地', fontfamily='KaiTi')

    axes[0].set_xlim(-100, 700)
    axes[0].set_ylim(-30, 70)
    axes[0].set_xticks([])
    axes[0].set_yticks([])
    axes[0].set_frame_on(False)

    axes[1].plot([0, 10], [300, 300], 'g--')
    axes[1].set_xlim(0, 10)
    axes[1].set_ylim(0, 800)
    axes[1].set_xticks((0, 4, 10))
    axes[1].set_yticks((300, 600))
    axes[1].set_xlabel('时间(h)', fontfamily='KaiTi')
    axes[1].set_ylabel('距离(Km)', fontfamily='KaiTi')


def animate(t):
    # print(t)
    x_a, x_b = 0, 0

    if t == 0:
        xdata.clear()
        ydata.clear()

    x_a = pointA + speedA * t
    if x_a > pointB:
        x_b = pointB
    dot_a.set_data(x_a, 0)
    text_a.set_position((x_a, 5))

    x_b = (pointB - pointA) - speedB * t
    if x_b <=0:
        x_b = 0
    dot_b.set_data(x_b, 0)
    text_b.set_position((x_b, 5))

    xdata.append(t)
    ydata.append(abs(x_b - x_a))
    line_distance.set_data(xdata, ydata)
    text_distance.set_text('x: {:>4.1f}\ny: {:>4.1f}'.format(t, abs(x_b - x_a)))
    #return dot_a, dot_b, text_a, text_b, line_distance, text_distance


ani = animation.FuncAnimation(fig, animate, frames=frame_move, init_func=init_graph, interval=200, repeat=False)
ani.save('慢车与快车相向而行.gif')
plt.show()