0

I use Windows 10 / 64 / Google chrome

I found a good set-up for animation over Jupyter with the call %matplotlib notebook as here :

import numpy as np
import scipy.stats as st
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation

For exemple, this one is working pretty well :

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

But, weirdly the code below doesn't work while it's the same structure, it puzzles me :

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

Thanks for your help, best regards.

EDIT : You don't have the funciton fen(sample_sort[:n],h[n],x) it is a function from float to float taking a x in argument and returning a flot. The argument sample_sort[:n],h[n] it is just maths things I'm trying to understand some statistics anyway, you can remplace with line with what you want np.cos(N[:n]) for exemple.

EDIT : New code according to the suggestion :

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

EDIT 2:

I found a code over internet which does exactly what I would like

# 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()
3
  • 1
    There also is a function f() not defined, what sort of error does the code return? Commented May 3, 2021 at 8:02
  • Indeed ! You can choose f = np.cos. And there's no error but the thing is there's no animation, I only get the plot : plot = plt.plot(X, [f(x) for x in X], c = "y", label = "densité") Commented May 3, 2021 at 8:04
  • lines.set_data(X, np.array([fen(sample_sort[:n],h[n],x) for x in X]))In the animation function, the length of X and Y need to be the same, so it should be X[:n]. Commented May 3, 2021 at 13:41

1 Answer 1

3

What I want to draw is a curve at random because the actual state of the function is unknown. The basic structure looks like this, so please modify it based on this.

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

Sign up to request clarification or add additional context in comments.

28 Comments

Cheers, I fancy : ax.set_title("n = {}".format(n)) in your code because even if you return lines, lines2 your function still provide a legend. Your code works on my laptop.
But mine still doesn't work, I add it in the first post. It means I have a empty figure
X is set to 150, but x and y need to be the same, so I set mine to 100.
Also, you need to set the drawing range of the graph, so you need to modify it to the range of your function. ax = plt.axes(xlim=(-5, 5), ylim=(-1, 1))
It shouldn't be a problem as my f takes place as plt.axes(xlim=(-4,4), ylim=(0, 0.6))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.