Skip to content Skip to sidebar Skip to footer

How To Plot Multiple Animated Functions On The Same Plot With Matplotlib?

i want to plot two animated functions on the same plot to compare between two functions , lets say for example exp(-x2) and exp(x2) i know how to animate a function here is the cod

Solution 1:

As mentioned in the comment, adding another line will work. Here is a working example with exp(-x^2) and exp(x^2), I also changed the limits to see both better:

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


fig, ax = plt.subplots()
xdata, ydata0, ydata1 = [], [], []
ln0, = plt.plot([], [], 'r', animated=True)
ln1, = plt.plot([], [], 'b', animated=True)
f = np.linspace(-3, 3, 200)

definit():
    ax.set_xlim(-3, 3)
    ax.set_ylim(-0.25, 10)
    ln0.set_data(xdata,ydata0)
    ln1.set_data(xdata,ydata1)
    return ln0, ln1

defupdate(frame):
    xdata.append(frame)
    ydata0.append(np.exp(-frame**2))
    ydata1.append(np.exp(frame**2))
    ln0.set_data(xdata, ydata0)
    ln1.set_data(xdata, ydata1)
    return ln0, ln1,

ani = FuncAnimation(fig, update, frames=f,
                    init_func=init, blit=True, interval=2.5, repeat=False)
plt.show()

For the gif below I changed the plt.show() line to be ani.save('animated_exp.gif', writer='imagemagick') and changed the interval to be 25.

gif created with example code

Post a Comment for "How To Plot Multiple Animated Functions On The Same Plot With Matplotlib?"