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
def demo():
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.scale(200, 200)
context.set_line_width(0.04)
context.move_to(x, y)
context.curve_to(x1, y1, x2, y2, x3, y3)
context.stroke()
context.set_source_rgba(1, 0.2, 0.2, 0.6)
context.set_line_width(0.02)
context.move_to(x, y)
context.line_to(x1, y1)
context.move_to(x2, y2)
context.line_to(x3, y3)
context.stroke()
return context
demo()
Using 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:
Comments
Add a comment: