Py.Cafe

fomightez/

matplotlib_animated_plot

Matplotlib Dynamic Sine Plot

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import panel as pn
import matplotlib.pyplot as plt
import numpy as np

pn.extension()

# Create initial plot
fig, ax = plt.subplots(figsize=(8, 4))
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

# Start with empty line
line, = ax.plot([], [])

# Wrap in Panel
mpl_pane = pn.pane.Matplotlib(fig, tight=True)

# Counter for animation
counter = {'i': 0}

def update():
    i = counter['i']
    if i < len(x):
        # Draw line from left to right
        line.set_data(x[:i+1], y[:i+1])
        counter['i'] += 1
    else:
        # Reset to start over
        counter['i'] = 0
        line.set_data([], [])
    
    mpl_pane.param.trigger('object')
    
# Update every 50ms for smooth drawing
pn.state.add_periodic_callback(update, period=100)

# Display
mpl_pane.servable()