logo

... matplotlib: func



Notes

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

Feedback? See an issue? Something unclear? Feel free to mention it here.



If you want to be kept up to date, consider signing up for the newsletter.