I’m available for freelance work. Let’s talk »

Drawing Cairo SVG in a Jupyter notebook

Sunday 27 January 2019This is more than five years old. Be careful.

Quick tip: if you want to draw figures using Cairo in a Jupyter notebook, here’s how to do it, at least this was how I did it:

from io import BytesIO

import cairo
import IPython.display

svgio = BytesIO()
with cairo.SVGSurface(svgio, 200, 200) as surface:
    # These lines are copied verbatim from the
    # pycairo page: https://pycairo.readthedocs.io
    context = cairo.Context(surface)
    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()
    # end of pycairo copy
IPython.display.SVG(data=svgio.getvalue())

Comments

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.