qewton.visualization.renderers.matplotlib package

Module contents

Matplotlib renderer: MatplotlibRenderer and its artists.

class qewton.visualization.renderers.matplotlib.MatplotlibRenderer(theme: Theme = Theme(background_color='#ffffff', text_color='#14181c', line_color='#14181c', grid_color='rgba(20,24,28,0.12)', font_family='Latin Modern Roman, CMU Serif, Georgia, serif', font_size_title=16, font_size_axes=14, font_size_labels=12, plot_width=400, plot_height=320, show_grid=False, show_zero_line=False, show_legend=True, legend_box=False, show_axis_line=True, axis_box=False, marker_size=6, line_width=1.25, opacity_default=0.8, surface_opacity=0.9, wireframe_opacity=0.3, geometry_color='#ebe2d9', vector_color='#14181c', primary_color_palette=['#f38f7f', '#fddb91', '#99bcdf', '#a18e7f', '#f9b381', '#8d89ba', '#94c9ad'], sequential_cmap=cmaps.meadow, diverging_cmap=cmaps.redblue, cyclic_cmap=cmaps.phase, node_color_by_type={'constraint': {'fill': '#aed6be', 'border': '#94c9ad'}, 'datanode': {'fill': '#fee1a5', 'border': '#fddb91'}, 'graphnode': {'fill': '#b7d2e6', 'border': '#99bcdf'}}, node_color_default='#b6a595', card_corner_radius=0.12, card_port_inner_radius=0.056, card_port_outer_radius=0.096, card_port_ring_radius=0.072, card_depth=0.04, card_line_width=1.0, card_title_font_size=11, card_title_font_family='Arial, Helvetica, sans-serif', card_edge_formula_size=8, graph_px_per_unit=110.0), usetex: bool = False, dpi: int = 100)[source]

Bases: Renderer

Draws a Figure with Matplotlib as a matplotlib.figure.Figure, without pyplot: drawing changes no global state and opens no window.

Text is written as mathtext, which renders the core’s $...$ math in Computer Modern without a LaTeX installation; the theme applies to every figure the renderer draws or writes, never globally.

A self-contained output embeds one TimeAxis or SliderAxis as frames: the snapshot of each state is drawn into the existing artists, and the title names the state (HTML: Matplotlib’s JavaScript player; GIF). Other controls keep their current state, with the Figure’s warning.

Parameters:
  • theme – Colors, fonts and sizes of everything drawn.

  • usetex – Whether LaTeX renders all text, instead of mathtext.

  • dpi – Resolution of the figure and of raster images.

Raises:

RuntimeError – If usetex is set and no latex is installed.

Notes

Not drawn: parallel coordinates and graph layouts.

artists: dict = {(<class 'qewton.visualization.plots.result.ArrowResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.Arrow2DArtist'>, (<class 'qewton.visualization.plots.result.ArrowResult'>, 3): <class 'qewton.visualization.renderers.matplotlib.primitives.Arrow3DArtist'>, (<class 'qewton.visualization.plots.result.BarResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.BarArtist'>, (<class 'qewton.visualization.plots.result.HeatmapResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.HeatmapArtist'>, (<class 'qewton.visualization.plots.result.ImageResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.ImageArtist'>, (<class 'qewton.visualization.plots.result.LineResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.Line2DArtist'>, (<class 'qewton.visualization.plots.result.LineResult'>, 3): <class 'qewton.visualization.renderers.matplotlib.primitives.Line3DArtist'>, (<class 'qewton.visualization.plots.result.MarkerResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.MarkerArtist'>, (<class 'qewton.visualization.plots.result.MarkerResult'>, 3): <class 'qewton.visualization.renderers.matplotlib.primitives.MarkerArtist'>, (<class 'qewton.visualization.plots.result.SurfaceResult'>, 2): <class 'qewton.visualization.renderers.matplotlib.primitives.FlatMeshArtist'>, (<class 'qewton.visualization.plots.result.SurfaceResult'>, 3): <class 'qewton.visualization.renderers.matplotlib.primitives.SurfaceArtist'>}
embeddable: tuple[type, ...] = (<class 'qewton.visualization.axes.TimeAxis'>, <class 'qewton.visualization.axes.SliderAxis'>)
max_embedded: int | None = 1
style() → AbstractContextManager[source]

The theme as a matplotlib.rc_context. Fonts and math are resolved when the figure is rendered, so every method drawing or writing the figure runs in it.

Returns:

The context.

Return type:

contextlib.AbstractContextManager

text(text: str | None) → str | None[source]

A text of the core as this renderer writes it into titles, axes, legends and colorbars.

Parameters:

text – A text, possibly with $...$ parts.

Returns:

The text, as plain text if mathtext cannot render

it (with a warning); unchanged with LaTeX.

Return type:

str or None

setup(figure) → None[source]

See setup().

draw(key, result, cell, visible: bool = True) → None[source]

See draw(); the legend entry is written as text().

hide(key) → None[source]

See hide().

create_backend_figure(figure) → Figure[source]

See Renderer.create_backend_figure.

Cells sharing a position axis with an earlier 2D cell share its Matplotlib axis, so they zoom together.

draw_axes(cell) → None[source]

See draw_axes().

draw_legend(entries: dict, cell) → None[source]

See draw_legend().

Drawn by draw_layout(), which knows its room: right of the colorbars of its cell, with the symbol of the first artist of every label that has one (meshes draw none, see _has_legend_entry).

draw_colorbar(scale, title, ticks, cell, slot: int, visible: bool = True) → None[source]

See draw_colorbar().

The colorbar is created by draw_layout(), which knows its room; until then its settings are kept.

draw_layout() → None[source]

See draw_layout().

The figure is sized from the plot sizes and the estimated room beside them (space); the grid’s columns and rows get the plot sizes as ratios, and constrained layout places everything when rendering, so a plot area may miss its size by what the estimate misses. A colorbar is an Axes inside its cell’s, right of its plot area, so it is as tall whatever its size. The figure title stands centered over the plot areas.

clear_embeddings() → None[source]

See clear_embeddings().

snapshot(keys, cells, scales) → tuple[dict, dict, dict][source]

See snapshot().

Returns:

``({key: (result, cell, visible)}, {(row, col): (cell,

axes settings)}, {id(scale): colorbar settings})``, as drawn last.

Return type:

tuple

animate(time_axis, snapshots) → None[source]

See animate().

The states become frames shown for the time axis’s duration each (frame weights apply to GIFs only), playing in a loop.

apply_slider(slider, snapshots) → None[source]

See apply_slider().

The states become frames, chosen with the frame slider.

show() → None[source]

See show().

A notebook gets the figure as html() at its own size, scrolling where it is wider than the output (notebook_html()); elsewhere it opens in a window of Matplotlib’s backend, animated if a control is embedded.

html(full_html: bool = True) → str[source]

The figure as HTML: Matplotlib’s JavaScript player of the frames if a control is embedded, else an inline SVG image.

Parameters:

full_html – A whole page, else an element to embed.

Returns:

The HTML.

Return type:

str

save_html(path) → None[source]

See save_html(); the page needs no scripts.

save_image(path, format, **kwargs) → None[source]

See save_image(); e.g. "png", "svg" or "pdf", with savefig arguments.

save_gif(path, fps: float = 10, frame_weights=None) → None[source]

See save_gif().

Raises:

ValueError – If no control is embedded.

Submodules

qewton.visualization.renderers.matplotlib.primitives module

Matplotlib artists for the primitive Results, one per Result class and number of position components.

An artist draws a Result into the Axes of its cell as Matplotlib objects (MatplotlibArtist.draw_into()); updating removes them and draws anew, at the same place in the drawing order. Colors are continuous: Matplotlib maps values through a colormap per element, so no value bins are needed. Colorbars are drawn by the renderer, never by an artist.

qewton.visualization.renderers.matplotlib.primitives.COLORBAR_LABEL = 'colorbar'

The label of a colorbar’s Axes.

qewton.visualization.renderers.matplotlib.primitives.cell_label(cell) → str[source]

The label of a cell’s Axes, by which artists find them.

Parameters:

cell (Cell) – The cell.

Returns:

E.g. "cell-1-2".

Return type:

str

qewton.visualization.renderers.matplotlib.primitives.axes_of(backend_figure, cell) → Axes[source]

The Axes of a cell in a figure built by the renderer.

Parameters:
  • backend_figure (matplotlib.figure.Figure) – The figure.

  • cell (Cell) – The cell.

Returns:

Its Axes.

Return type:

matplotlib.axes.Axes

qewton.visualization.renderers.matplotlib.primitives.colorbar_axes(backend_figure, cell=None) → list[Axes][source]

The Axes of the colorbars beside a cell’s plot area, in a figure built by the renderer; Axes inside the cell’s.

Parameters:
  • backend_figure (matplotlib.figure.Figure) – The figure.

  • cell (Cell, optional) – The cell; None for those of every cell.

Returns:

Their Axes, left to right.

Return type:

list of matplotlib.axes.Axes

class qewton.visualization.renderers.matplotlib.primitives.MatplotlibArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: Artist

Base class of the Matplotlib artists: owns the objects it drew into one Axes.

Parameters:
  • axes – The Axes drawn into.

  • objects – The Matplotlib objects drawn.

  • zorder – Place in the drawing order, kept across updates.

axes

The Axes drawn into.

Type:

matplotlib.axes.Axes

objects

The Matplotlib objects drawn.

Type:

list

Notes

Subclasses implement draw_into().

classmethod draw_into(axes: Axes, result, theme) → list[source]

Draw result into axes.

Parameters:
  • axes – The Axes.

  • result (Result) – The Result to draw.

  • theme (Theme) – The renderer’s theme.

Returns:

The Matplotlib objects drawn; the first carries the

legend entry.

Return type:

list

classmethod create(backend_figure, result, cell, theme) → MatplotlibArtist[source]

See create().

Artists are drawn in the order they are created, as in Plotly, whatever their kind.

update(backend_figure, result, cell, theme) → None[source]

See update().

set_visible(backend_figure, visible: bool) → None[source]

See set_visible().

class qewton.visualization.renderers.matplotlib.primitives.HeatmapArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a HeatmapResult as a pcolormesh of cells centered on the grid points.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.FlatMeshArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a SurfaceResult in 2D: colored triangles interpolated between their points (tripcolor with Gouraud shading), or filled in one color; plus the edges if shown.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.SurfaceArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a SurfaceResult in 3D as a Poly3DCollection, each triangle in the color of the mean value of its points, or in one shaded color; with edges if shown.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.Line2DArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a LineResult in 2D as a LineCollection; a colored segment takes the mean value of its end points.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.Line3DArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a LineResult in 3D as a Line3DCollection, colored as in 2D.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.MarkerArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a MarkerResult in 2D or 3D as a scatter.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.BarArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws a BarResult as bar: bars 0.8 of the smallest spacing wide.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.ImageArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws an ImageResult as a pcolormesh of RGB(A) cells centered on the grid points, so the spacing may vary.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.Arrow2DArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws an ArrowResult in 2D as a quiver whose arrows are as long as their vectors in data units.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

class qewton.visualization.renderers.matplotlib.primitives.Arrow3DArtist(axes: Axes, objects: list, zorder: float)[source]

Bases: MatplotlibArtist

Draws an ArrowResult in 3D as a quiver whose arrows are as long as their vectors, each in one color.

classmethod draw_into(axes, result, theme) → list[source]

See MatplotlibArtist.draw_into().

qewton.visualization.renderers.matplotlib.style module

The theme as Matplotlib settings: rcParams, colormaps and color norms.

Theme sizes are in pixels, as Plotly takes them; Matplotlib takes points (points()). The LaTeX look needs no LaTeX installation: text is set in the theme’s serif fonts, falling back to Matplotlib’s bundled Computer Modern (cmr10), and math in mathtext’s Computer Modern.

qewton.visualization.renderers.matplotlib.style.color(css: str)[source]

A theme color as Matplotlib takes it: CSS rgb()/rgba() as a tuple, anything else (e.g. "#rrggbb") unchanged.

Parameters:

css – The color.

Returns:

A Matplotlib color.

Return type:

str or tuple

qewton.visualization.renderers.matplotlib.style.PIXELS_PER_INCH = 96

Pixels per inch of the theme’s sizes, as in a browser.

qewton.visualization.renderers.matplotlib.style.points(pixels: float) → float[source]

A theme size in pixels as points (72 per inch), at PIXELS_PER_INCH.

Parameters:

pixels – Size in pixels.

Returns:

Size in points.

Return type:

float

qewton.visualization.renderers.matplotlib.style.fonts(font_family: str) → dict[source]

rcParams of a CSS-like font list, e.g. "Latin Modern Roman, Georgia, serif": its fonts in order, then the fallbacks.

Parameters:

font_family – Comma-separated font names, possibly ending with a generic family.

Returns:

font.family and the font list of that family.

Return type:

dict

qewton.visualization.renderers.matplotlib.style.rc_params(theme, usetex: bool = False) → dict[source]

The rcParams of a theme.

Parameters:
  • theme (Theme) – The theme.

  • usetex – Whether LaTeX renders all text.

Returns:

rcParams, for matplotlib.rc_context.

Return type:

dict

qewton.visualization.renderers.matplotlib.style.colormap(resolved) → Colormap[source]

The Matplotlib colormap of a colormap resolved by a theme.

Parameters:

resolved – The result of resolve_cmap(): [position, color] stops, or a Matplotlib colormap name.

Returns:

The colormap.

Return type:

matplotlib.colors.Colormap

Raises:

ValueError – If a name is no Matplotlib colormap.

qewton.visualization.renderers.matplotlib.style.norm(scale: ColorScale) → Normalize[source]

The norm mapping transformed values of a color scale (log10 for a log scale) onto its colormap.

Parameters:

scale – The trained color scale.

Returns:

The norm of its transformed range.

Return type:

matplotlib.colors.Normalize

qewton.visualization.renderers.matplotlib.style.mapped(values: ndarray, scale: ColorScale) → ndarray[source]

Values in the space a norm() maps: log10 for a log scale, NaN where they cannot be drawn.

Parameters:
  • values – Values bound to scale.

  • scale – The color scale.

Returns:

The transformed values, masked where NaN.

Return type:

numpy.ndarray

qewton.visualization.renderers.matplotlib.text module

Texts as Matplotlib displays them.

Matplotlib’s mathtext renders the core’s texts as they are, plain text mixed with $...$ math. It knows a subset of LaTeX: a text whose math it cannot parse is shown as plain text, with a warning. Plain text falls back to Matplotlib’s Computer Modern (cmr10), which holds other glyphs at a few ASCII characters (TeX’s encoding, e.g. a dot accent at _); these are written as math.

qewton.visualization.renderers.matplotlib.text.as_mathtext(text: str | None) → str | None[source]

text for mathtext: its math unchanged if mathtext parses it, else the whole text as plain text, with a warning; in plain parts the characters cmr10 lacks are written as math.

Parameters:

text – A text, possibly with $...$ parts.

Returns:

The text to display.

Return type:

str or None

Warns:

UserWarning – If mathtext cannot parse the math of text.