如何在Funcanimation中获得fill_between形状?

时间:2017-06-07 12:53:05

标签: python animation matplotlib

我想制作一个动态图,曲线下方的区域会在绘制曲线时变色。

我搜索了一下,发现我应该以某种方式创建一个补丁。但是,我不理解他们给出的任何例子,所以让我在这里用我的具体例子来问:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import pylab as p

data = np.loadtext('datafile.dat', delimiter=',')
A = data[:,1]
B = data[:,2]

fig = plt.figure(figsize=(25,5), dpi=80)
ax = plt.axes(xlim=(0, 3.428), ylim=(-1,1))
line, = ax.plot([], [], lw=5)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = A[0:(i-1)*400]
    y = B[0:(i-1)*400]
    line.set_data(x,y)
    # Here is the problem. I would now like to add the following line
    # p.fill_between(x, 0, y, facecolor = 'C0', alpha = 0.2)
    return line,

anim = animation.FuncAnimation(fig,animate, init_func=init, frames = 857, interval=20, blit=True)

我希望有人可以帮我解决问题,或者至少指出我正确的方向。

所以我的问题是:如何在没有任何错误的情况下添加评论部分?

1 个答案:

答案 0 :(得分:1)

假设您需要blit = True,您还需要返回fill_between生成的补丁。

p = plt.fill_between(x, y, 0)
return line, p,

完整的工作示例:

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

X = np.linspace(0,3.428, num=250)
Y = np.sin(X*3)

fig = plt.figure(figsize=(13,5), dpi=80)
ax = plt.axes(xlim=(0, 3.428), ylim=(-1,1))
line, = ax.plot([], [], lw=5)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = X[0:(i-1)]
    y = Y[0:(i-1)]
    line.set_data(x,y)
    p = plt.fill_between(x, y, 0, facecolor = 'C0', alpha = 0.2)
    return line, p,

anim = animation.FuncAnimation(fig,animate, init_func=init, 
                               frames = 250, interval=20, blit=True)

plt.show()