【问题标题】:Python matplotlib.animation Jupyter NotebookPython matplotlib.animation Jupyter Notebook
【发布时间】:2021-05-03 07:25:44
【问题描述】:

我使用 Windows 10 / 64 / 谷歌浏览器

我在 Jupyter 上找到了一个很好的动画设置,调用 %matplotlib 笔记本,如下所示:

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) 它是一个从浮点到浮点的函数,在参数中接受 x 并返回一个浮点数。参数 sample_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()

【问题讨论】:

  • 还有一个函数f()没有定义,代码返回什么错误?
  • 确实!您可以选择 f = np.cos。而且没有错误,但问题是没有动画,我只得到情节: plot = plt.plot(X, [f(x) for x in X], c = "y", label = "densité")
  • lines.set_data(X, np.array([fen(sample_sort[:n],h[n],x) for x in X]))动画函数中,X和Y的长度需要相同,所以应该是X[:n]。

标签: python matplotlib jupyter-notebook matplotlib-animation


【解决方案1】:

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

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

【讨论】:

  • 干杯,我想: ax.set_title("n = {}".format(n)) 在您的代码中,因为即使您返回行,lines2 您的函数仍然提供图例。您的代码可以在我的笔记本电脑上运行。
  • 但是我的还是不行,我在第一篇加了。这意味着我有一个空的身影
  • X 设置为 150,但 x 和 y 需要相同,所以我设置为 100。
  • 另外,你需要设置图形的绘制范围,所以你需要修改为你的函数的范围。 ax = plt.axes(xlim=(-5, 5), ylim=(-1, 1))
  • 最好一次性整理出来。您为什么不发布一个单独的问题,关于您现在在做什么、您想要输出的图形图像以及您正在使用的功能?让我们接受我的回答并继续前进。我认为目前没有人有精力回答。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-24
  • 2020-02-13
  • 2021-05-27
相关资源
最近更新 更多