Andrew Jenkins' blog C++ with Plots in Jupyter Notebook
Post

C++ with Plots in Jupyter Notebook

Jupyter Notebook is one of my favorite programming environments. It feels like a combination of a REPL (read-eval-print loop) and a scientific notebook. It rewards literate programming: you invite the user to step through the important logic of your program with you, rather than hiding it behind a curtain. They see the intermediate outputs, and are encouraged to experiment and tweak. It’s great for learning and teaching. Here’s what a notebook looks like:

Jupyter sine example in Python

Jupyter is great for dynamic languages with REPL loops, like Python and R. It’s also great for programs that do data analysis, mathematical modelling, plotting and other data science-y things, like Python and R. It used to be called IPython, because it worked just for Python. Sensing a language theme here?

It turns out you can use Jupyter Notebook with more than just Python and R. I wanted to use it with C++ and found that the xeus-cling kernel worked, with a little bit of poking. In Jupyter-speak, the kernel is the binding to a particular language (and in this case, a C++ REPL called Cling that is based on Clang and LLVM). This got me line-by-line C++ support in Jupyter.

But one of the best parts about Jupyter is graphics. Jupyter makes it easy to plot results, rather than just printing off numbers. There are a few popular plotting libraries for Jupyter when you’re using Python or R, but I didn’t find any great ones for C++. So I found a way to use my favorite Python plotting library (matplotlib) from C++, in Jupyter. This is based on some C/C++ to python bindings called matplotlib-cpp.

When combined, you can code in C++ but plot as good as everyone using matplotlib and python.

Here’s the above example rewritten in C++:

Jupyter sine example in C++

In practice, I don’t think you’d use C++ for examples this simple. Numpy (and the other python math and data science libraries) are very convenient and efficient. However, if there’s a good reason to write your program/library in C++, now you can have a notebook interface to it, as well.

You can check it out here, and you can run a pre-built docker container:

1
docker run --rm -it -v ${PWD}/notebooks:/notebooks -p 8889:8889 andrewjjenkins/matplotlibcpp-jupyter:latest
This post is licensed under CC BY 4.0 by the author.