3

所以我正在尝试创建一些随时间移动的高斯图的动画。我的基本动画也按照我的预期工作。但后来我想遮蔽高斯曲线下的区域。我使用 ax.fill 函数对其进行着色。但相反,它只是遮蔽了创建曲线的绘图矢量,并且变得一团糟。任何建议或帮助将不胜感激

import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import matplotlib.animation as animation
import pylab as p

Gamma=0.0005
q=1.6e-19
m=0.067*9e-31
B=10
Ec=(1.0567e-34)*B/m
#e=2.78

#E0=0+(1.0567e-34)*x*i/m

fig, ax = plt.subplots()

n = 3 #number of lines
x = np.arange(0, 3.6e-3, 1.7e-5)        # x-array, third number is interval here, x is energy
lines = [ax.plot(x, np.e**(-(x-((1.0567e-34)*1*1/m))**2/Gamma**2))[0]for _ in range(n)]


def animate(i):
    for d, line in enumerate(lines):
        p=(d+1)/2.
        line.set_ydata(np.e**((-(x-((1.0567e-34)*p*i/m))**2)/Gamma**2))
        ax.fill(x,(np.e**(-(x-((1.0567e-34)*p*i/m))**2/Gamma**2)), "b")# update the data
    return lines


#Init only required for blitting to give a clean slate.
def init():
    for line in lines:
        line.set_ydata(np.ma.array(x, mask=True))
    return lines

ani = animation.FuncAnimation(fig, animate, np.arange(0, 2.5, .01), init_func=init,
    interval=10, blit=True)
Writer = animation.writers['ffmpeg']
writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)

ani.save('QHanimati.mp4', writer=writer)



plt.show()

所以当前代码运行一个动画,给出这样的东西。 曲线

我希望它使曲线上方的区域保持白色。

谢谢。

4

1 回答 1

4

您需要注意,保存的动画是在blit=False. 所以发生的事情是填充全部添加到画布上。

一种解决方案是在添加下一个之前删除前一个(因为set_data填充不直接存在类似的东西)。

同样,我们将创建一个填充列表,并实际使用fill_betweenfill我们可以使用它来删除填充并添加新填充。

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


Gamma=0.0005
q=1.6e-19
m=0.067*9e-31
B=10
Ec=(1.0567e-34)*B/m

fig, ax = plt.subplots()

n = 3 #number of lines
x = np.arange(0, 3.6e-3, 1.7e-5)        # x-array, third number is interval here, x is energy
lines = [ax.plot(x, np.e**(-(x-((1.0567e-34)*1*1/m))**2/Gamma**2), zorder=i+3)[0] for i in range(n)]
fills = [ax.fill_between(x,0,(np.e**(-(x-((1.0567e-34)*1*1/m))**2/Gamma**2)), facecolor=lines[i].get_color(), zorder=i+3) for i in range(n)]


def animate(i):
    for d, line in enumerate(lines):
        p=(d+1)/2.
        line.set_ydata(np.e**((-(x-((1.0567e-34)*p*i/m))**2)/Gamma**2))
        fills[d].remove()
        fills[d] = ax.fill_between(x,0,(np.e**(-(x-((1.0567e-34)*p*i/m))**2/Gamma**2)), facecolor=lines[d].get_color(), zorder=d+3)# update the data

    return lines + fills


#Init only required for blitting to give a clean slate.
def init():
    for line in lines:
        line.set_ydata(np.ma.array(x, mask=True))
    return lines

ani = animation.FuncAnimation(fig, animate, np.arange(0, 2.5, .01), init_func=init,
    interval=10, blit=True)
#Writer = animation.writers['ffmpeg']
#writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)
#
#ani.save('QHanimati.mp4', writer=writer)

plt.show()

在此处输入图像描述

于 2017-06-22T22:07:15.853 回答