Calmcode - matplotlib: func

Func

1 2 3 4 5 6 7 8 9

The plt.subplot function is nice but we're stuck with a lot of code for just a single chart. To keep the notebook clean it is preferable to wrap this into a function such that we can re-use it without repeating our code. This is also a nice opportunity to add some titles to the chart.

import numpy as np
import matplotlib.pylab as plt

def grid_plots(mus, sigmas):
    plt.figure(figsize=(7,7))
    for i, mu in enumerate(mus):
        for j, sigma in enumerate(sigmas):
            x = np.random.normal(mu, sigma, (1000,))
            plt.subplot(len(mus), len(sigmas), len(sigmas) * i + j + 1)
            plt.hist(x, bins=30)
            plt.title(f"$\mu$={mu}, $\sigma$={sigma}")
            plt.xlim(min(mus) - max(sigmas)*3, max(mus) + max(sigmas)*3)

grid_plots(mus=[0.1, 0.3, 0.5], sigmas=[0.1, 0.4])