15

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.

bongbang
  • 1,610
  • 4
  • 18
  • 34
  • The library [tikzpy](https://tikzpy.readthedocs.io/en/latest/) for Python might do the job – fco Feb 01 '23 at 20:15

1 Answers1

13

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.

Jakob
  • 19,815
  • 6
  • 75
  • 94
  • Using Anaconda3, what directory am I cloning the TikZ repo into? – Christopher Turnbull Oct 17 '17 at 11:31
  • @ChristopherTurnbull when looking at the github page the prefered installation method is now to use pip – Jakob Oct 17 '17 at 14:01
  • On Google Colab, " !pip install git+git://github.com/mkrphys/ipython-tikzmagic.git %load_ext tikz_magic " yields "Successfully built ipython-tikzmagic" but then "ModuleNotFoundError: No module named 'tikz_magic'" How to handle that? – sh37211 Feb 06 '21 at 15:48
  • The library [tikzpy](https://tikzpy.readthedocs.io/en/latest/) for Python might do the job – fco Feb 01 '23 at 20:15