Jupyter: how to make simple illustrations

bongbang picture bongbang · Jun 2, 2015 · Viewed 12.4k times · Source

I am learning to use Jupyter/IPython Notebook as an electronic notebook. Sometimes I need simple illustrations to go along with my calculations, e.g. arrows to represent vector quantities. That's the kind of illustration for which TikZ would be used if we were in Latex. Having tried the TikZ magic extension and failed, I wonder if there's a more native (Python) way to do this. I don't see Matplotlib as the right tool for this sort of thing (correct me if I'm wrong).

If you think TikZ magic is indeed the way to go and I should try to get it to work, then do say so. Thanks.

Answer

Jakob picture Jakob · Jun 5, 2015

TikZ (prefered solution)

If you're already familiar with TikZ the respective magic is probably the best option. To use it, simply follow the installation instruction in this repo (pip install git+git://github.com/mkrphys/ipython-tikzmagic.git) and load the extension as shown in on the githib page with %load_ext tikzmagic.
I just tried with IPython 3.1 and it works fine. Of course you have to have pdflatex available.

Matplotlib

If you want to draw simple arrows matplotlib can be used as well and is, of course, more pythonic than TikZ. A really simple example based on this example could look like

import matplotlib.pyplot as plt
%matplotlib inline
plt.axis('off')
plt.arrow(0, 0, 0.5, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k');

For more technical plots with lots of arrows and dimensions, I totally agree with you that matplotlib is not be preferred.

Other alternatives

There is also an asymptote magic found here. I haven't tried this yet, though.

Finally, you could use svgs either written in the notebook (hints see this question, or using Inkscape or similar and embed the resulting svg-file via the from IPython.display import SVG.