Skip to content

figure

figure #

Figure — a raster chart drawn with matplotlib and kept as a PNG cg.Image.

  1. Open. Entering the with block lays out one or more stacked panels in the house style: white paper, dark ink, type a phone can read at full width.
  2. Draw. The body draws on figure.axes (or figure.panels) with matplotlib's own vocabulary.
  3. Keep. Leaving the block renders the figure into figure.image, a PNG in the current call's workspace — the value an interceptor serves to the app or ImageViewer shows on a page.

DPI = 100 module-attribute #

Pixels per inch: a figure width pixels wide is width / DPI inches.

INK = '#212529' module-attribute #

Text, axes and the default line colour.

MUTED = '#6c757d' module-attribute #

Tick labels and other secondary text.

RULE = '#dee2e6' module-attribute #

Grid lines.

STYLE = {'figure.facecolor': 'white', 'axes.facecolor': 'white', 'axes.edgecolor': INK, 'axes.labelcolor': INK, 'axes.titlecolor': INK, 'axes.spines.top': False, 'axes.spines.right': False, 'axes.grid': True, 'grid.color': RULE, 'grid.linewidth': 1.0, 'xtick.color': MUTED, 'ytick.color': MUTED, 'text.color': INK, 'font.size': 18, 'axes.titlesize': TITLE_SIZE, 'axes.labelsize': 18, 'legend.fontsize': 16, 'legend.frameon': False, 'lines.linewidth': 3} module-attribute #

The house style: plain, high-contrast, and legible on a phone at full width.

TITLE_SIZE = 26 module-attribute #

The title's size, in points.

Figure #

A matplotlib figure that becomes a PNG cg.Image when its with block ends.

@cg.pure_function("coverage_chart/1")
def coverage_chart(hours: cg.Array[float], need: cg.Array[float]) -> cg.Image:
    with cgui.Figure("When to photograph") as figure:
        figure.axes.plot(list(hours), list(need))
        figure.axes.set_xlabel("Hour")
    return figure.image
Source code in capturegraph-ui/capturegraph_ui/figures/figure.py
class Figure:
    """A matplotlib figure that becomes a PNG ``cg.Image`` when its ``with`` block ends.

    ```python
    @cg.pure_function("coverage_chart/1")
    def coverage_chart(hours: cg.Array[float], need: cg.Array[float]) -> cg.Image:
        with cgui.Figure("When to photograph") as figure:
            figure.axes.plot(list(hours), list(need))
            figure.axes.set_xlabel("Hour")
        return figure.image
    ```
    """

    def __init__(
        self,
        title: str | None = None,
        *,
        width: int = 1200,
        height: int = 900,
        panels: Sequence[float] = (1.0,),
    ) -> None:
        """A figure to draw in a ``with`` block.

        Args:
            title: A short title over the figure.
            width: The image's width, in pixels.
            height: The image's height, in pixels.
            panels: The relative height of each panel, top to bottom; panels
                share their horizontal axis.
        """
        self.title = title
        self.width = width
        self.height = height
        self.heights = list(panels)
        self.panels: list[Axes] = []
        self._figure: MatplotlibFigure | None = None
        self._image: cg.Image | None = None

    @property
    def axes(self) -> Axes:
        """The first (or only) panel."""
        return self.panels[0]

    @property
    def image(self) -> cg.Image:
        """The finished PNG.

        Raises:
            RuntimeError: If the ``with`` block has not ended yet.
        """
        if self._image is None:
            raise RuntimeError("a Figure's image exists once its with block ends")
        return self._image

    def __enter__(self) -> Self:
        """Take the house style and lay out the panels."""
        import matplotlib
        from matplotlib.figure import Figure as MatplotlibFigure

        _STYLE_LOCK.acquire()
        self._style = matplotlib.rc_context(STYLE)
        self._style.__enter__()
        figure = MatplotlibFigure(
            figsize=(self.width / DPI, self.height / DPI),
            dpi=DPI,
            layout="constrained",
        )
        if self.title is not None:
            figure.suptitle(self.title, x=0.02, ha="left", fontsize=TITLE_SIZE)
        self.panels = list(
            figure.subplots(
                len(self.heights),
                1,
                sharex=True,
                squeeze=False,
                height_ratios=self.heights,
            )[:, 0]
        )
        self._figure = figure
        return self

    def __exit__(
        self,
        kind: type[BaseException] | None,
        error: BaseException | None,
        traceback: TracebackType | None,
    ) -> None:
        """Render the figure into ``image`` unless the block raised, then release the style."""
        try:
            if kind is None and self._figure is not None:
                image = cg.Image.new("png")
                self._figure.savefig(image, format="png", dpi=DPI)
                self._image = image
        finally:
            self._style.__exit__(kind, error, traceback)
            _STYLE_LOCK.release()

axes property #

The first (or only) panel.

image property #

The finished PNG.

Raises:

Type Description
RuntimeError

If the with block has not ended yet.

__enter__() #

Take the house style and lay out the panels.

Source code in capturegraph-ui/capturegraph_ui/figures/figure.py
def __enter__(self) -> Self:
    """Take the house style and lay out the panels."""
    import matplotlib
    from matplotlib.figure import Figure as MatplotlibFigure

    _STYLE_LOCK.acquire()
    self._style = matplotlib.rc_context(STYLE)
    self._style.__enter__()
    figure = MatplotlibFigure(
        figsize=(self.width / DPI, self.height / DPI),
        dpi=DPI,
        layout="constrained",
    )
    if self.title is not None:
        figure.suptitle(self.title, x=0.02, ha="left", fontsize=TITLE_SIZE)
    self.panels = list(
        figure.subplots(
            len(self.heights),
            1,
            sharex=True,
            squeeze=False,
            height_ratios=self.heights,
        )[:, 0]
    )
    self._figure = figure
    return self

__exit__(kind, error, traceback) #

Render the figure into image unless the block raised, then release the style.

Source code in capturegraph-ui/capturegraph_ui/figures/figure.py
def __exit__(
    self,
    kind: type[BaseException] | None,
    error: BaseException | None,
    traceback: TracebackType | None,
) -> None:
    """Render the figure into ``image`` unless the block raised, then release the style."""
    try:
        if kind is None and self._figure is not None:
            image = cg.Image.new("png")
            self._figure.savefig(image, format="png", dpi=DPI)
            self._image = image
    finally:
        self._style.__exit__(kind, error, traceback)
        _STYLE_LOCK.release()

__init__(title=None, *, width=1200, height=900, panels=(1.0,)) #

A figure to draw in a with block.

Parameters:

Name Type Description Default
title str | None

A short title over the figure.

None
width int

The image's width, in pixels.

1200
height int

The image's height, in pixels.

900
panels Sequence[float]

The relative height of each panel, top to bottom; panels share their horizontal axis.

(1.0,)
Source code in capturegraph-ui/capturegraph_ui/figures/figure.py
def __init__(
    self,
    title: str | None = None,
    *,
    width: int = 1200,
    height: int = 900,
    panels: Sequence[float] = (1.0,),
) -> None:
    """A figure to draw in a ``with`` block.

    Args:
        title: A short title over the figure.
        width: The image's width, in pixels.
        height: The image's height, in pixels.
        panels: The relative height of each panel, top to bottom; panels
            share their horizontal axis.
    """
    self.title = title
    self.width = width
    self.height = height
    self.heights = list(panels)
    self.panels: list[Axes] = []
    self._figure: MatplotlibFigure | None = None
    self._image: cg.Image | None = None