flex_source_code = "https://github.com/danielfrg/jupyter-flex/blob/master/examples/widgets/mpl-histogram.ipynb"
import numpy as np
import ipywidgets as widgets
from IPython.display import clear_output, display
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
%matplotlib inline
set_matplotlib_formats('svg')
np.random.seed(42)
# fig_size = plt.rcParams["figure.figsize"]
# fig_size[0] = 6 * 3
# fig_size[1] = 4 * 3
# plt.rcParams["figure.figsize"] = fig_size
mu_label = widgets.Label(value="Mean:")
mu_var = widgets.BoundedIntText(value=100, min=10, max=300)
sigma_label = widgets.Label(value="Sigma:")
sigma_var = widgets.BoundedIntText(value=15, min=10, max=50)
bins_label = widgets.Label(value="Bins:")
bins_var = widgets.IntSlider(value=50, min=1, max=100, step=1)
widgets.VBox([mu_label, mu_var, sigma_label, sigma_var, bins_label, bins_var])
out = widgets.Output()
def on_value_change(change):
mu = mu_var.value
sigma = sigma_var.value
num_bins = bins_var.value
with out:
fig, ax = plt.subplots()
# the histogram of the data
x = mu + sigma * np.random.randn(437)
n, bins, patches = ax.hist(x, num_bins, density=1)
# add a 'best fit' line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('X')
ax.set_ylabel('Probability density')
ax.set_title(f'Histogram with: mu={mu}, sigma={sigma}, bins={num_bins}')
clear_output(wait=True)
plt.show(fig)
mu_var.observe(on_value_change, names="value")
sigma_var.observe(on_value_change, names="value")
bins_var.observe(on_value_change, names="value")
on_value_change(None)
out