{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "In this tutorial notebook we'll learn how to:\n", "* Plot the gaussian density for a specific $\\mu$ and $\\sigma$\n", "* Use the FloatSlider widget in `ipywidgets` to represent $\\mu$ and $\\sigma$ values\n", "* Layout the density plot along with the sliders using HBox and VBox layout objects available in `ipywidgets`\n", "* Link the sliders to the plot so that the plot gets updated when the values of $\\mu$ and $\\sigma$ change" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from scipy.stats import norm\n", "\n", "from ipywidgets import FloatSlider, HBox, VBox\n", "import bqplot.pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.linspace(-10, 10, 200)\n", "y = norm.pdf(x)\n", "\n", "# plot the gaussian density\n", "title_tmpl = 'Gaussian Density (mu = {} and sigma = {})'\n", "pdf_fig = plt.figure(title=title_tmpl.format(0, 1))\n", "pdf_line = plt.plot(x, y, 'm', stroke_width=3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# use two sliders to represent mu and sigma\n", "mu_slider = FloatSlider(description='mu', value=0, min=-5, max=5, step=.1)\n", "sigma_slider = FloatSlider(description='sigma', value=1, min=0.1, max=5, step=.1)\n", "\n", "slider_layout = HBox([mu_slider, sigma_slider])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def update_density(change):\n", " new_mu = mu_slider.value\n", " new_sigma = sigma_slider.value\n", " # update the y attribute of the plot with the new pdf\n", " # computed using new mu and sigma values\n", " pdf_line.y = norm.pdf(x, new_mu, new_sigma)\n", " \n", " # also update the fig title\n", " pdf_fig.title = title_tmpl.format(new_mu, new_sigma)\n", "\n", "# register the above callback with the 'value' trait of the sliders\n", "for slider in [mu_slider, sigma_slider]:\n", " slider.observe(update_density, 'value')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# now put all the widgets together into a simple dashboard\n", "# the plot should update now when the slider values are updated!\n", "final_layout = VBox([pdf_fig, slider_layout])\n", "final_layout" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 2 }