Commit 7aaa3c5e authored by Matthieu Boileau's avatar Matthieu Boileau
Browse files

Add an interactive plot

parent 41c97b24
numpy
matplotlib
ffmpeg
jupyter
\ No newline at end of file
jupyter
ipywidgets
\ No newline at end of file
......@@ -32,6 +32,18 @@ def generate_walk(nstep: int):
return x, y
def create_figure(nstep: int):
"""Return a figure and plot area for a nstep-walk"""
# Create figure and plot area
fig, ax = plt.subplots()
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_title(f'{nstep}-nstep random walk')
ax.set_aspect('equal', 'datalim')
ax.grid(True)
return fig, ax
def generate_animation(nstep: int = 50):
"""return a nstep-random walk animation"""
......@@ -46,19 +58,14 @@ def generate_animation(nstep: int = 50):
x, y = generate_walk(nstep)
# Create figure and plot area
fig, ax = plt.subplots()
# a continuous line to draw walk path
# create figure and plot area
fig, ax = create_figure(nstep)
# plot a continuous line for walk path
path, = ax.plot(x, y)
# a round-symbol spot to show current position
# plot a round-symbol spot for current position
spot, = ax.plot(x[0], y[0], 'o')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_title(f'{nstep}-nstep random walk')
ax.set_aspect('equal', 'datalim')
ax.grid(True)
anim = animation.FuncAnimation(fig,
func=update_path,
frames=nstep,
......@@ -69,6 +76,18 @@ def generate_animation(nstep: int = 50):
return anim
def plot_walk(nstep):
"""Plot a nstep-random walk in a figure"""
x, y = generate_walk(nstep)
fig, ax = create_figure(nstep)
path, = ax.plot(x, y) # a line for path
# symbols for initial (squared) and final (round) position
starting_point, = ax.plot(x[0], y[0], 's', color=path.get_color())
ending_point, = ax.plot(x[-1], y[-1], 'o')
if __name__ == '__main__':
anim = generate_animation(100)
plt.show()
%% Cell type:markdown id: tags:
# A simple 2D random walk
Some initializations (import [`srw.py`](../edit/srw.py)).
%% Cell type:code id: tags:
``` python
%matplotlib inline
import srw
from matplotlib import rcParams
from matplotlib import pyplot as plt
rcParams['figure.figsize'] = (10., 8.) # Enlarge figure
rcParams['animation.html'] = 'html5' # to render animation in notebook
```
%% Cell type:markdown id: tags:
Create and play a matplotlib animation for a $nstep$-step random walk starting at $(x, y) = (0, 0)$.
%% Cell type:code id: tags:
``` python
anim = srw.generate_animation(nstep=100)
plt.close(anim._fig) # Close the initial figure to display only the animation figure
anim # Now play
```
%% Cell type:markdown id: tags:
Plot entire path for various $nstep$ values.
%% Cell type:code id: tags:
``` python
from ipywidgets import interact
import ipywidgets as widgets
interact(srw.plot_walk, nstep=widgets.IntSlider(min=50, max=1000, step=50, value=50));
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment