I finally came up with a way I like to create PyCairo drawings in a Jupyter notebook.
A few years ago I wrote here about how to draw Cairo SVG in a Jupyter notebook. That worked, but wasn’t as convenient as I wanted. Now I have a module that manages the PyCairo contexts for me. It automatically handles the displaying of SVG and PNG directly in the notebook, or lets me write them to a file.
The module is drawing.py.
The code looks like this (with a sample drawing copied from the PyCairo docs):
from drawing import cairo_context
with cairo_context(200, 200, format="svg") as context:
x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9
x2, y2, x3, y3 = 0.6, 0.1, 0.9, 0.5
context.curve_to(x1, y1, x2, y2, x3, y3)
context.set_source_rgba(1, 0.2, 0.2, 0.6)
demo() in a notebook cell will draw the SVG. Nice.
The key to making this work is Jupyter’s special methods _repr_svg_, _repr_png_, and a little _repr_html_ thrown in also.
The code is at drawing.py. I created it so that I could play around with Truchet tiles: