首页 > 解决方案 > Matplotlib animation with time-dependent parameter

问题描述

I am new using python and I would like to ask you a problem that I have with my current code. I am solving a partial differential equation (1D in space) and I want to make an animation at each time for the given numerical solution, but I don't want to save all the arrays of the solution at each time (because this is not efficient)

For simplicity I just show you the analytical solution of the differential equation.

I have tried to make a plot for each time steep trying to make an animation, but as I have read in other places it's not too much efficient due to the plt.pause()

import numpy as np
import math
from matplotlib import pyplot as plt

pi = math.pi
xmin = 0.0
xmax = 10.0
N = 100 #number of points
x = np.arange(xmin, xmax , (xmax-xmin)/N)

def solution(t):
    p = np.exp(-x**2/(4*k*t))/(np.sqrt(4.*pi*k*t))
    return p

t_final = 10.0
t_initial = 0.0
t = t_initial
dt = 0.1
k = 1.0
while t<t_final:
    t +=dt
    pp = solution(t)

    plt.ion()
    plt.xlabel('x')
    plt.ylabel('P')
    plt.plot(x, pp, 'r-',label = "t=%s" % t)
    plt.legend(loc='upper right')
    plt.draw()
    plt.pause(10**(-20))
    plt.show()
    plt.clf()

Do you know how can be re-implemented my code to make an animation (and save it) without save the data ?

标签: pythonmatplotlibanimation

解决方案


Here is how to use FuncAnimation to generate the desired animation

import numpy as np
import math
from matplotlib import pyplot as plt

pi = math.pi
xmin = 0.0
xmax = 10.0
N = 100 #number of points
x = np.arange(xmin, xmax , (xmax-xmin)/N)

t_initial = 0.0
t_final = 10.0
dt = 0.1
k = 1.0

fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('P')
plotLine, = ax.plot(x, np.zeros(len(x))*np.NaN, 'r-')
plotTitle = ax.set_title("t=0")
ax.set_ylim(0,1.)
ax.set_xlim(xmin,xmax)


def solution(t):
    p = np.exp(-x**2/(4*k*t))/(np.sqrt(4.*pi*k*t))
    return p


def animate(t):
    pp = solution(t)
    plotLine.set_ydata(pp)
    plotTitle.set_text(f"t = {t:.1f}")
    #ax.relim() # use if autoscale desired
    #ax.autoscale()
    return [plotLine,plotTitle]



ani = animation.FuncAnimation(fig, func=animate, frames=np.arange(t_initial, t_final+dt, dt), blit=True)
plt.show()

enter image description here


推荐阅读