简体   繁体   English

如何使用matplotlib在同一图上绘制多个动画函数?

[英]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(-x 2) and exp(x 2) i know how to animate a function here is the code i used to animate the function我想在同一个图上绘制两个动画函数以比较两个函数,例如 exp(-x 2) 和 exp(x 2) 我知道如何为函数设置动画,这是我用来为函数设置动画的代码

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并且通过相同的方法我们可以绘制另一个函数但是我们如何在同一个图上显示它们

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:这是一个使用 exp(-x^2) 和 exp(x^2) 的工作示例,我还更改了限制以更好地查看两者:

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,我将plt.show()行更改为ani.save('animated_exp.gif', writer='imagemagick')并将间隔更改为 25。

使用示例代码创建的 gif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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