简体   繁体   中英

How to stop second plot from showing up in matplotlib?

I am trying to plot an animation of a physics system. I've worked out the equations and it plots, but there's a second plot I don't want that keeps showing up and I can't get it to stop.

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

Here's the output:

在此处输入图像描述

The plot I want to get rid of is the one I circled with red. This is the entirety of my code, so it should be completely reproducible.

I tried several variations of trimming the plotting code but I wasn't able to debug why it's happening.

How can I get rid of this second plot?

A simple plt.close() before your call to ani will do the job.

Last few lines:

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

Demo:

在此处输入图像描述

More info at this link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM