4

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 code i used to animate the function

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
%matplotlib qt
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'r', animated=True)
f = np.linspace(-3, 3, 200)
def init():
    ax.set_xlim(-3, 3)
    ax.set_ylim(-0.25, 2)
    ln.set_data(xdata,ydata)
    return ln,
def update(frame):
    xdata.append(frame)
    ydata.append(np.exp(-frame**2))
    ln.set_data(xdata, ydata)
    return ln,
ani = FuncAnimation(fig, update, frames=f,enter code here
                    init_func=init, blit=True, interval = 2.5,repeat=False)
plt.show()



enter code here

and by the same method we can plot the other function but how do we show them on the same plot

3
  • 1
    Add another line, like ln2, = plt.plot(...) and update that line in the same way you're doing it for ln already. Commented Jan 17, 2020 at 21:42
  • i tried but got this error unindent does not match any outer indentation level Commented Jan 17, 2020 at 22:02
  • That indentation error is just basic python. Make sure to always use the same number of spaces (best 4) for indentation. Commented Jan 17, 2020 at 22:22

1 Answer 1

6

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)

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

def update(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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.