Skip to content
Projects

plasma_plots.plotly_backend

Interactive Plotly versions of the plots: backend="plotly".

Every accessor plot that draws with Matplotlib (array.plasma.plot.*, dataset.plasma.plot.*, out.plot.*) takes backend="plotly". The plot is drawn with Matplotlib as usual, off screen, and the drawn figure is converted into a Plotly figure: the same data, color limits, fits, reference curves, labels and layout, but with hover values, zoom and, for animations and viewers, a slider in the browser. The two backends cannot disagree about what they show, because there is only one drawing code path.

result = phi.plasma.plot.slice( … coords=“physical”, plane=“XY”, t=-1, eta3=0, backend=“plotly” … ) result.fig # a plotly.graph_objects.Figure result.save(“phi.html”) # a standalone page; .png/.pdf/.svg need kaleido

the default for every plot from now on

plasma_plots.set_backend(“plotly”)

Plots return a PlotResult with either backend (fit_results and data included); animations and viewers return one too, whose figure has a slider. Plotly is optional: pip install "plasma-plots[plotly]".

For a web page, result.save("phi.plotly.json") writes a web figure ([web_figure()][web_figure]): Plotly JSON without plotly.js and without a look of its own, which the PlotlyFigure component of the max-models docs theme embeds in the site’s colours, animations included (pip install "plasma-plots[web]").

The conversion itself is also available for any Matplotlib figure drawn with the plotting functions: [to_plotly()][to_plotly], [animation_to_plotly()][animation_to_plotly] and to_plotly().

What converts: lines, markers and scatters (also colored by a value), bars (ax.bar, ax.barh and histograms), meshes (heatmaps on rectilinear grids; on mapped, curvilinear grids an image of the mesh with the values under the cursor), images of values (imshow with a colormap, as heatmaps over their extent), contour lines, quivers, colored line collections, horizontal and vertical lines and bands, annotations, colorbars, legends, log axes, twin axes, 3-D lines and scatters, shared and equal-aspect axes, and titles. Mathtext labels ($\omega$, $p_0$) become Unicode and sub/superscripts. Anything else is left out with a [ConversionWarning][ConversionWarning].

Attributes

NameDescription
BACKENDSNo description.
IMAGE_PIXELSNo description.
MATH_MODESNo description.
PAGE_PIXELSNo description.
PLOTLY_MIMENo description.
PX_PER_INCHNo description.
PX_PER_PTNo description.

Classes

NameDescription
ConversionWarningA part of a Matplotlib figure that has no Plotly counterpart here and is left out.

Functions

NameDescription
animation_to_plotlyConvert a Matplotlib animation of the plotting functions into a Plotly figure with frames.
bareStrip a Plotly figure to its data, for a header picture or a front page.
display_bundleThe notebook output of a Plotly figure: its JSON, an HTML copy and a text line.
get_backendReturn the backend of plots that do not pass backend= themselves.
get_mathReturn how the formulas of labels reach Plotly figures.
mathjax_source"cdn" for a figure with a LaTeX label (see set_math()), else False.
plotly_textTurn a Matplotlib label into Plotly text.
resolve_backendThe backend a plot draws with: backend, or the default if it is None.
save_postersWrite pictures of a Plotly figure for a docs page, for light and dark mode.
set_backendSet the backend of every plot that does not pass backend= itself.
set_mathSet how the formulas of labels (Matplotlib's $...$ mathtext) reach Plotly figures.
to_plotlyConvert a drawn Matplotlib figure into an interactive Plotly figure.
viewer_to_plotlyConvert a slider viewer into a Plotly figure with one slider.
web_figureA Plotly figure as a web figure, the format of maxplotlib.web.
with_backendGive an accessor plot method the backend option.

BACKENDSattributemodule attribute#

BACKENDS = ('matplotlib', 'plotly', 'tikz')

IMAGE_PIXELSattributemodule attribute#

IMAGE_PIXELS = 1200

MATH_MODESattributemodule attribute#

MATH_MODES = ('unicode', 'latex')

PAGE_PIXELSattributemodule attribute#

PAGE_PIXELS = 800

PLOTLY_MIMEattributemodule attribute#

PLOTLY_MIME = 'application/vnd.plotly.v1+json'

PX_PER_INCHattributemodule attribute#

PX_PER_INCH = 100.0

PX_PER_PTattributemodule attribute#

PX_PER_PT = PX_PER_INCH / 72.0

ConversionWarningclass#

class ConversionWarning(UserWarning)

Bases: UserWarning

A part of a Matplotlib figure that has no Plotly counterpart here and is left out.

animation_to_plotlyfunction#

def animation_to_plotly(animation, *, labels=None, prefix: str | None = None, play: bool = True, strict: bool = False)

Convert a Matplotlib animation of the plotting functions into a Plotly figure with frames.

Every frame is drawn by the animation’s own update function and converted like a figure, so the frames show exactly what the Matplotlib animation shows; a slider (and Play/Pause buttons) steps through them.

Parameters

NameTypeDefaultDescription
animationmatplotlib.animation.FuncAnimationrequiredThe animation, e.g. from animate_slices().
labelssequence of strNoneOne slider label per frame. Default: the sweep values the animation was made for (for the animations of this package), else the frame numbers.
prefixstrNoneShown before the current label, e.g. "t = ". Default: the sweep’s name.
playboolTrueAdd Play and Pause buttons. Default: True.
strictboolFalseRaise instead of warning when a part of a frame cannot be converted. Default: False.

Returns

plotly.graph_objects.Figure
The first frame, with every frame in figure.frames.

Raises

ValueError
If the frames do not all have the same kinds of traces.

Examples

>>> animation = animate_slices(phi.isel(eta3=0), step=2)
>>> animation_to_plotly(animation).write_html("phi.html")

barefunction#

def bare(figure)

Strip a Plotly figure to its data, for a header picture or a front page.

The axes, ticks, grid, titles, legend, color bars, sliders and buttons go, the background becomes transparent and the margins zero: the counterpart of the "bare" Matplotlib style (see plasma_plots.styles). An animation keeps its frames.

Parameters

NameTypeDescription
figureplotly.graph_objects.FigureThe figure; changed in place.

Returns

plotly.graph_objects.Figure
The same figure.

Examples

>>> result = phi.plasma.plot.animation(x="x", y="y", backend="plotly")
>>> bare(result.fig).write_json("docs/public/plotly/hero.json")

display_bundlefunction#

def display_bundle(figure, *, title: str | None = None)

The notebook output of a Plotly figure: its JSON, an HTML copy and a text line.

application/vnd.plotly.v1+json is what JupyterLab renders and what docs sites built from the notebook embed as an interactive chart (the output’s metadata has the key "plotly-figure"); text/html loads plotly.js from its CDN for other front ends. With maxplotlib installed the JSON also carries the palette slots and hints of a web figure (web_figure()), so the docs site recolours it as it does a saved .plotly.json.

Parameters

NameTypeDefaultDescription
figureplotly.graph_objects.FigurerequiredThe figure.
titlestrNoneA caption, in the output’s "plotly-figure" metadata. Default: the figure’s caption (layout.meta["caption"]), if it has one.

Returns

tuple of dict
The MIME bundle and its metadata, as for IPython.display.display(..., raw=True).

get_backendfunction#

def get_backend() -> str

Return the backend of plots that do not pass backend= themselves.

Returns

str
"matplotlib" (the default), "plotly" or "tikz".

get_mathfunction#

def get_math() -> str

Return how the formulas of labels reach Plotly figures.

Returns

str
"unicode" (the default) or "latex".

mathjax_sourcefunction#

def mathjax_source(figure) -> str | bool

"cdn" for a figure with a LaTeX label (see set_math()), else False.

The include_mathjax of Plotly’s HTML export: a page of the figure loads MathJax from a CDN only when the figure has a formula to typeset.

Parameters

NameTypeDescription
figureplotly.graph_objects.FigureThe figure.

Returns

str or bool
"cdn" or False.

plotly_textfunction#

def plotly_text(text, *, math: str | None = None) -> str

Turn a Matplotlib label into Plotly text.

Mathtext ($\omega$, $p_0$) becomes Unicode and /; other <, > and & are escaped, newlines become
. In the "latex" mode of set_math() a label with a formula becomes one LaTeX formula instead, the text around it in \text{...}, for plotly.js to typeset with MathJax.

Parameters

NameTypeDefaultDescription
textstr or NonerequiredThe label.
math('unicode', 'latex')"unicode"How formulas are written. Default: the mode of set_math().

Returns

str
The Plotly text; "" for None.

Examples

>>> plotly_text(r"fit: $\gamma$ = 0.1")
'fit: γ = 0.1'
>>> plotly_text("$p_0$")
'p<sub>0</sub>'
>>> plotly_text(r"$\sigma_s$ [m$^2$]", math="latex")
'$\\sigma_s\\text{ [m}^2\\text{]}$'

resolve_backendfunction#

def resolve_backend(backend: str | None) -> str

The backend a plot draws with: backend, or the default if it is None.

Inside another plot (e.g. ArrayPlots.slice calling SliceView.slice) it is always "matplotlib": the outermost call converts the finished figure.

Parameters

NameTypeDefaultDescription
backend('matplotlib', 'plotly', 'tikz')"matplotlib"The backend asked for.

Returns

str
"matplotlib", "plotly" or "tikz".

save_postersfunction#

def save_posters(figure, stem, *, width: int = 800) -> list[str]

Write pictures of a Plotly figure for a docs page, for light and dark mode.

A page shows them until plotly.js has drawn the figure, and in its place without JavaScript (the poster and posterDark of the docs theme’s PlotlyFigure). Both have a transparent background and the theme’s text colours; an animation shows its first frame. Written by maxplotlib.web.write_posters; needs kaleido.

Parameters

NameTypeDefaultDescription
figureplotly.graph_objects.FigurerequiredThe figure.
stemstr or pathlib.PathrequiredThe files’ path without the extension: <stem>.png and <stem>.dark.png.
widthint800Width in pixels; the height follows the figure’s aspect ratio. Default: 800.

Returns

list of str
The paths written.

Raises

ImportError
If maxplotlib (with maxplotlib.web.write_posters) is not installed.

Examples

>>> save_posters(result.fig, "docs/public/plotly/energy")

set_backendfunction#

def set_backend(backend: str) -> str

Set the backend of every plot that does not pass backend= itself.

Parameters

NameTypeDefaultDescription
backend('matplotlib', 'plotly', 'tikz')"matplotlib"The new default ("tikz": see plasma_plots.tikz_backend).

Returns

str
The previous default, e.g. to restore it afterwards.

Raises

ValueError
If backend is not "matplotlib", "plotly" or "tikz".

Examples

>>> previous = plasma_plots.set_backend("plotly")
>>> phi.plasma.plot.slice(t=-1, eta3=0) # a Plotly figure
>>> plasma_plots.set_backend(previous)

set_mathfunction#

def set_math(mode: str) -> str

Set how the formulas of labels (Matplotlib’s $...$ mathtext) reach Plotly figures.

With "unicode" (the default) a formula becomes Unicode text with sub- and superscripts, which every Plotly front end shows. With "latex" a label with a formula is kept as LaTeX, one $...$ formula per label (the text around it in \text{...}), which plotly.js typesets with MathJax: on the max-models docs sites (the theme’s PlotlyFigure loads MathJax for such figures), in the pictures kaleido draws, and in the HTML pages save() writes (which load MathJax from a CDN). Hover labels, which plotly.js does not typeset, keep the Unicode form. JupyterLab may show the LaTeX as written. The mode applies when a figure is converted, so set it before plotting.

Parameters

NameTypeDefaultDescription
mode('unicode', 'latex')"unicode"The new mode.

Returns

str
The previous mode, e.g. to restore it afterwards.

Raises

ValueError
If mode is not "unicode" or "latex".

Examples

>>> plasma_plots.set_backend("plotly")
>>> plasma_plots.set_math("latex") # e.g. in the first cell of a docs notebook

to_plotlyfunction#

def to_plotly(figure, *, strict: bool = False)

Convert a drawn Matplotlib figure into an interactive Plotly figure.

Parameters

NameTypeDefaultDescription
figurematplotlib.figure.FigurerequiredA figure drawn by one of the plotting functions (or any figure with the artists they use, see plasma_plots.plotly_backend).
strictboolFalseRaise instead of warning when a part of the figure cannot be converted. Default: False.

Returns

plotly.graph_objects.Figure
The same content: traces for the data, shapes for lines and bands spanning an axes, annotations for text, a colorbar per Matplotlib colorbar.

Raises

ImportError
If plotly is not installed.

Examples

>>> result = plot_slice(phi.isel(t=-1, eta3=0))
>>> to_plotly(result.fig).write_html("phi.html")

viewer_to_plotlyfunction#

def viewer_to_plotly(viewer)

Convert a slider viewer into a Plotly figure with one slider.

The Matplotlib viewer has one slider per remaining dimension; a Plotly figure can combine only one, so exactly one dimension besides the two drawn may be left with more than one value.

Parameters

NameTypeDescription
viewerplasma_plots.plotting.InteractiveSliceViewerThe viewer (drawn or not).

Returns

PlotResult
The Plotly figure, with a slider over the remaining dimension (a static slice if there is none).

Raises

ValueError
If more than one dimension remains to slide over.

web_figurefunction#

def web_figure(figure, **hints) -> dict

A Plotly figure as a web figure, the format of maxplotlib.web.

Plotly JSON for a page of a max-models docs site: no template, no fixed size, transparent backgrounds, the palette position of each trace in a default colour (trace.meta["color_slot"]) and hints for the page in layout.meta["web"]. The theme’s PlotlyFigure component gives it the site’s colours in light and dark mode.

Parameters

NameTypeDefaultDescription
figureplotly.graph_objects.Figure or dictrequiredThe figure.
**hints{}title, alt (a text alternative), aspect (width over height) and white_plot (keep a white plot area and the figure’s own colours in dark mode), as for maxplotlib.web.web_figure. white_plot is off by default, also for a figure converted from Matplotlib: the theme draws its black and white in the page’s colours.

Returns

dict
data, layout and, for an animation, frames.

Raises

ImportError
If maxplotlib (with maxplotlib.web) is not installed.

Examples

>>> web = web_figure(result.fig, alt="Field energy over time")

with_backendfunction#

def with_backend(method)

Give an accessor plot method the backend option.

The decorated method declares backend=None in its signature (so that its docs and help() show it) and draws with Matplotlib as before; with backend="plotly" or backend="tikz" (or that default, see set_backend()) the decorator draws off screen and returns the converted result instead (see plasma_plots.tikz_backend). An ax given with either raises TypeError, since such a figure cannot be drawn into a Matplotlib axes.

Parameters

NameTypeDescription
methodcallableA method returning a PlotResult, a FuncAnimation or an InteractiveSliceViewer.

Returns

callable
The method with the backend option.