Python matplotlib.animation Jupyter笔记本

2024-04-25 00:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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()

Tags: ofinnumberforframesplotdefnp
1条回答
网友
1楼 · 发布于 2024-04-25 00:24:10

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

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())

enter image description here

相关问题 更多 >