python - 如何阻止第二个情节出现在 matplotlib 中?
问题描述
我正在尝试绘制物理系统的动画。我已经计算出方程式并绘制了图,但是我不希望第二个图不断出现,我无法让它停止。
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML
# Input constants
m = 10 # mass (kg)
L = 4 # length (m)
g = 9.81 # gravity (m/s^2)
dt = 0.1 # time step size (seconds)
t_max = 40 # max sim time (seconds)
num_steps = 1 + int(t_max/dt)
theta_0 = np.pi/2 # initial angle (radians)
theta_dot_0 = 0 # initial angular velocity (rad/s)
state0 = [theta_0,theta_dot_0]
# Get timesteps
time_index = np.arange(0, t_max + dt, dt)
def derivatives(state, time_index, L=L, m=m, g=g):
theta_dot = state[1]
theta_ddot = -g*np.sin(state[0])/L
return theta_dot,theta_ddot
output = integrate.odeint(derivatives, state0, time_index)
theta = output[:,0]
theta_dot = output[:,1]
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=True, xlim=(-2*L, 2*L), ylim=(-2*L, 2*L))
ax.set_aspect('equal')
ax.grid()
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
x = L*np.sin(theta)
y = -L*np.cos(theta)
def init():
# create empty object to put the points in
line.set_data([], [])
time_text.set_text('')
return line, time_text
def animate(t):
x_t = [0, x[t]]
y_t = [0, y[t]]
# add the point to the line
line.set_data(x_t, y_t)
# add the time text to plot
# time_template will be the text next to thetime
time_text.set_text(time_template % (t*dt))
return line, time_text
# we don't want the range of the steps to start at 0
# start it at one
ani = animation.FuncAnimation(fig, animate, range(1, num_steps),
interval=dt*1000, blit=True, init_func=init)
rc('animation', html='jshtml')
#ani.save('pendulum.mp4', fps=15)
ani
这是输出:
我想摆脱的情节是我用红色圈出的情节。这是我的全部代码,所以它应该是完全可重现的。
我尝试了几种修剪绘图代码的变体,但我无法调试它发生的原因。
我怎样才能摆脱这第二个情节?
解决方案
一个简单的plt.close()
在你打电话之前就ani
可以完成这项工作。
最后几行:
ani = animation.FuncAnimation(fig, animate, range(1, num_steps),
interval=dt*1000, blit=True, init_func=init)
rc('animation', html='jshtml')
#ani.save('pendulum.mp4', fps=15)
plt.close()
ani
演示:
更多信息在这个链接。
推荐阅读
- hadoop - 如何在动态 hdfs 目录上创建分区 hive 表
- swift - UICollectionView 在从 Web Api 加载数据之前运行
- angular - ionic4/angular8 的 routerlink 而不是(点击)
- python - 围绕一个正方形滚动一个圆圈
- reactjs - 反应 useEffect 钩子无限循环
- reactjs - 一个数组的一个输出和嵌套在其中的数组的不同输出
- python - 在 docker 容器中运行时进程突然堆积内存
- angular - 角反应形式材料日期选择器手动输入格式DD/MM/YYYY
- javascript - 打字时如何使表格中所有单元格的生长高度相同?
- c++ - OpenGL - Reading cursor position correctly but cant draw line from it