Last active
March 23, 2018 01:41
-
-
Save braaannigan/0d35fa8f862fad617a48515f1c1beaf5 to your computer and use it in GitHub Desktop.
Interactive plots with holoviews in a jupyter notebook - needs to be in two separate code cells, see text for details
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The following must be executed in a jupyter notebook rather than a shell environment. | |
# Use numpy to work with arrays | |
import numpy as np | |
# Use scipy.stats to do plot some statistical data | |
import scipy.stats as stats | |
import holoviews as hv | |
# Holoviews builds on top of either the Matplotlib or Bokeh plotting library. Choose to use Bokeh | |
# in these plots as interactive plots work very well with Bokeh | |
hv.notebook_extension('bokeh') | |
# Create some fake, normally distributed data with mean = 2, standard deviation = 2 and 1000 elements | |
fake_data = np.random.normal(2,2,1000) | |
# Create a histogram of that data | |
freqs, edges = np.histogram(fake_data, bins=30, density=True) | |
# Set out the range of values for the x-axis for the line plots of the distribution below | |
x_range = np.arange(-10,10,1e-1) | |
###### NEW CELL IN NOTEBOOK ############################## | |
%%opts Histogram (alpha=0.3) | |
# The line above starting with %%opts needs to be the first line in the new cell. | |
# It sets the transparency of the histogram in the plot. Setting this option is | |
# not necessary for the interactive plot, it just makes the plot a bit nicer. | |
# Plot the histogram of the data to compare with the interactive line plots below | |
normal_hist = hv.Histogram((freqs, edges), kdims=['x'], vdims=['Probability density'], group='Histogram of samples') | |
# Create a dictionary that maps from a tuple where the values are the mean and standard deviation to | |
# a line plot that is the normal distribution with this mean and standard deviation | |
normal_curves = {(mu,sigma): hv.Curve( (x_range, stats.norm.pdf(x_range,mu,sigma)), | |
kdims=['x'],vdims=['Probability density']) | |
for mu in np.arange(-6,6,0.5) | |
for sigma in np.arange(0.5,4,0.5)} | |
# Create a list with the dimension names that will be shown on the plot | |
kdims = [('dim1', 'Mu'), ('dim2', 'Sigma')] | |
# Feed the dictionary that maps the tuple of mean and standard deviation to line plots into a HoloMap | |
interactive_plot = hv.HoloMap(normal_curves,kdims=kdims) | |
# Plot the histogram (a static plot) against the interactive Holomap | |
normal_hist*interactive_plot | |
# You should have a plot of the histogram along with two sliders so that you can see which | |
# values of the mean and standard deviation of the normal distribution match the data best. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment