To get a virtualenv set up with the appropriate packages I needed to:
$ mkvirtualenv blogpost_ipython
$ pip install -U distribute
$ pip install matplotlib
$ pip install ipython
$ pip install pyzmq
$ pip install jinja2
Now my pip freeze looks like this:
$ pip freeze
Jinja2==2.7.3
MarkupSafe==0.23
argparse==1.2.1
backports.ssl-match-hostname==3.4.0.2
distribute==0.7.3
ipython==2.1.0
matplotlib==1.3.1
nose==1.3.3
numpy==1.8.1
pyparsing==2.0.2
python-dateutil==2.2
pyzmq==14.3.1
six==1.7.2
tornado==3.2.2
wsgiref==0.1.2
Then make a directory for this work and start the notebook server:
$ mkdir blogpost_ipython
$ cd blogpost_ipython
$ ipython notebook
and I get a message that says (among other things)
2014-06-17 09:04:15.816 [NotebookApp] The IPython Notebook is running at: http://localhost:8888/
and a tab in chrome opens. The page has a button 'New Notebook'. Clicking that gets you a notebook that you can add new cells to. When you add Python code to the cell and press the play button in the toolbar (or press Shift+Enter) the code is executed. When opening a notebook for the first time, don't forget to execute all the cells so that for example the imports are performed.
Now we're up and running we can get to the good stuff. First some cells to do our imports:
from IPython.html.widgets import interact
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Now the magic. We want to pass as arguments to interact
a function that draws a plot, and a description of the arguments that the plot drawing function takes. First define the plot drawing function (this is just straight matplotlib.pyplot
):
def plot_sine(n):
x = np.arange(0, 20, 0.1);
y = np.sin(x/n)
plt.plot(x, y)
Now call interact
like so, and you should see a plot in the notebook that has a widget allowing you to vary the value of n
. Note however that the interactive part only works if you're running the notebook server, and you have executed the code cells. Otherwise you will just see a picture of the plot.
interact(plot_sine, n=(1,10, 0.1))
<function __main__.plot_sine>
And I think that's amazingly cool!