Sagebrush · Examples · Notebooks

matplotlib

Line plots, histograms, bar charts and an animation with matplotlib.

notebook · Python · intro · by Sagebrush · MIT license

plotsdata

Download (ZIP)Source on GitHub

Preview

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 201)
plt.plot(x, np.sin(x), label='sin')
plt.plot(x, np.cos(x), '--', label='cos')
plt.title('Figures show when the cell ends'); plt.legend(); plt.grid(True)
<Figure size 640x480 with 1 Axes>
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(2)
data = rng.normal(size=5000)
fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.5))
a.hist(data, bins=40, edgecolor='white')
a.set_title('5000 normal samples')
b.scatter(data[:300], data[300:600], c=data[600:900], s=18)
b.set_title('scatter, colored by a third sample')
<Figure size 900x350 with 2 Axes>
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 3.5))
plt.bar(['Python', 'Sage', 'JavaScript', 'Rust'], [42, 17, 30, 12], color=['C0', 'C1', 'C2', 'C3'])
plt.ylabel('cells run today')
<Figure size 600x350 with 1 Axes>
# matplotlib.animation.FuncAnimation
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots(figsize=(7, 3))
x = np.linspace(0, 6.4, 160)
line, = ax.plot([], [], lw=2)
ax.set_xlim(0, x[-1]); ax.set_ylim(-1.2, 1.2)
def update(k):
    line.set_data(x, np.sin(3 * x - k / 4) * np.cos(x / 2))
    ax.set_title(f'frame {k}')
ani = FuncAnimation(fig, update, frames=50, interval=40)
<Figure size 700x300 with 1 Axes>
# ipywidgets' interact works too
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact

@interact(k=(0.0, 1.0), w=(1, 10))
def damped(k=0.2, w=4):
    t = np.linspace(0, 10, 500)
    plt.figure(figsize=(7, 3))
    plt.plot(t, np.exp(-k * t) * np.cos(w * t))
    plt.ylim(-1, 1); plt.title(f'k = {k:.2f}, w = {w}')
<Figure size 700x300 with 1 Axes>

Files

Open the ZIP's notebook in Sagebrush (File, Open) to run and change it.