首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何阻止在matplotlib中显示第二个图?

如何阻止在matplotlib中显示第二个图?
EN

Stack Overflow用户
提问于 2020-07-25 20:44:03
回答 1查看 31关注 0票数 1

我正在尝试绘制一个物理系统的动画。我已经解出了方程式,画出了图,但是还有第二个图,我不希望它一直出现,我不能让它停下来。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

下面是输出:

我想摆脱的情节是我用红色圈出的那个。这是我的全部代码,所以它应该是完全可重现的。

我尝试了几种修剪绘图代码的变体,但我无法调试为什么会发生这种情况。

我怎样才能摆脱第二个情节呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-25 21:23:38

在调用ani之前使用一个简单的plt.close()就可以完成这项工作。

最后几行:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

演示:

更多信息请访问this链接。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63093399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文