Python matplotlib.animation Jupyter笔记本

Python matplotlib.animation Jupyter笔记本,python,matplotlib,jupyter-notebook,matplotlib-animation,Python,Matplotlib,Jupyter Notebook,Matplotlib Animation,我使用Windows 10/64/Google chrome 我发现通过调用%matplotlib笔记本在Jupyter上设置动画效果很好,如下所示: import numpy as np import scipy.stats as st %matplotlib notebook import matplotlib.pyplot as plt import matplotlib.animation as animation 例如,这一个非常有效: n = 100 X = st.norm(0,1

我使用Windows 10/64/Google chrome

我发现通过调用%matplotlib笔记本在Jupyter上设置动画效果很好,如下所示:

import numpy as np
import scipy.stats as st
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
例如,这一个非常有效:

n = 100
X = st.norm(0,1).rvs(200)
number_of_frames = np.size(X)

def update_hist(num, second_argument):
    plt.cla()
    plt.hist(X[:num], bins = 20)
    plt.title("{}".format(num))
    plt.legend()

fig = plt.figure()
hist = plt.hist(X)

ani = animation.FuncAnimation(fig, update_hist, number_of_frames, fargs=(X, ), repeat = False )
plt.show()
但是,奇怪的是,下面的代码在结构相同的情况下无法工作,这让我感到困惑:

X = np.linspace(-5,5, 150)
number_of_frames = np.size(X)
N_max = 100
N = np.arange(1,N_max+1)
h = 1/np.sqrt(N)

def update_plot(n, second_argument):
    #plt.cla()
    plt.plot(X, [f(x) for x in X], c = "y", label = "densité")
    plt.plot(X, [fen(sample_sort[:n],h[n],x) for x in X], label = "densité")
    plt.title("n = {}".format(n))

fig = plt.figure(6)
plot = plt.plot(X, [f(x) for x in X], c = "y", label = "densité")
    
ani = animation.FuncAnimation(fig, update_plot, number_of_frames, fargs=(X, ), repeat = False )
plt.show()
谢谢你的帮助,问好

编辑:您没有函数fen(sample_sort[:n],h[n],x),它是一个从float到float的函数,在参数中取x并返回flot。参数示例_sort[:n],h[n]这只是数学问题,我正在尝试理解一些统计数据,你可以用你想要的np.cos(n[:n])作为例子

编辑:根据建议新建代码:

N_max = 100
X = np.linspace(-5,5, N_max )
number_of_frames = np.size(X)
N = np.arange(1,N_max+1)
h = 1/np.sqrt(N)

def update_plot(n):
    #plt.cla()
    lines.set_data(X, np.array([fen(sample_sort[:n],h[n],x) for x in X]))
    ax.set_title("n = {}".format(n))
    return lines

fig = plt.figure()

ax = plt.axes(xlim=(-4, 4), ylim=(-0.01, 1))
ax.plot(X, np.array([f(x) for x in X]), 'y-', lw=2, label="d")
lines, = ax.plot([], [], 'b--', lw=3, label="f")

ani = animation.FuncAnimation(fig, update_plot, number_of_frames, repeat = False )
plt.show()
编辑2:

我在网上找到了一个代码,它完全符合我的要求

# Fermi-Dirac Distribution
def fermi(E: float, E_f: float, T: float) -> float:
    return 1/(np.exp((E - E_f)/(k_b * T)) + 1)

# Create figure and add axes
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)

# Get colors from coolwarm colormap
colors = plt.get_cmap('coolwarm', 10)

# Temperature values
T = np.array([100*i for i in range(1,11)])

# Create variable reference to plot
f_d, = ax.plot([], [], linewidth=2.5)

# Add text annotation and create variable reference
temp = ax.text(1, 1, '', ha='right', va='top', fontsize=24)

# Set axes labels
ax.set_xlabel('Energy (eV)')
ax.set_ylabel('Fraction')

# Animation function
def animate(i):
    x = np.linspace(0, 1, 100)
    y = fermi(x, 0.5, T[i])
    f_d.set_data(x, y)
    f_d.set_color(colors(i))
    temp.set_text(str(int(T[i])) + ' K')
    temp.set_color(colors(i))

# Create animation
ani = animation.FuncAnimation(fig, animate, frames=range(len(T)), interval=500, repeat=False)

# Ensure the entire plot is visible
fig.tight_layout()

# show animation
plt.show()

我想画的是一条随机曲线,因为函数的实际状态未知。基本结构如下所示,请在此基础上进行修改

import numpy as np
import scipy.stats as st
# %matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# from IPython.display import HTML
# from matplotlib.animation import PillowWriter

X = np.linspace(-5,5, 100)
number_of_frames = np.size(X)
N_max = 100
N = np.arange(1,N_max+1)
h = 1/np.sqrt(N)

def update_plot(n):
    #plt.cla()
    lines.set_data(X[:n], h[:n])
    lines2.set_data(X[:n], h[:n]*-1)
    ax.set_title("n = {}".format(n))
    return lines, lines2

fig = plt.figure()
ax = plt.axes(xlim=(-5, 5), ylim=(-1, 1))
lines, = ax.plot([], [], 'y-', lw=2, label="densité")
lines2, = ax.plot([], [], 'b--', lw=3, label="densité2")

ani = animation.FuncAnimation(fig, update_plot, frames=number_of_frames, repeat=False )
plt.show()
# ani.save('lines_ani2.gif', writer='pillow')

# plt.close()
# HTML(ani.to_html5_video())

还有一个未定义的函数f(),代码返回的是什么类型的错误?确实!您可以选择f=np.cos。没有错误,但是没有动画,我只得到绘图:plot=plt.plot(X,[f(X)代表X中的X],c=“y”,label=“densité”)
line.set_data(X,np.array([fen(sample_sort[:n],h[n],X)代表X中的X])
在动画函数中,X和y的长度需要相同,所以应该是
X[:n]
。干杯,我喜欢在代码中使用ax.set_title(“n={}.format(n)),因为即使返回行,函数中的行2仍然提供图例。你的代码可以在我的笔记本电脑上运行。但我的代码仍然无法运行,我在第一篇文章中添加了它。这意味着我有一个空的figureX设置为150,但是x和y需要相同,所以我将我的设置为100。此外,您需要设置图形的绘图范围,因此需要将其修改为函数的范围
ax=plt.axes(xlim=(-5,5),ylim=(-1,1))
最好一劳永逸地解决它。你为什么不单独问一个问题,关于你现在正在做什么,你想要输出的图形图像,以及你正在使用的功能?让我们接受我的答案,继续前进。我认为在这一点上没有人有精力回答。