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
| Name | Description |
|---|---|
BACKENDS | No description. |
IMAGE_PIXELS | No description. |
MATH_MODES | No description. |
PAGE_PIXELS | No description. |
PLOTLY_MIME | No description. |
PX_PER_INCH | No description. |
PX_PER_PT | No description. |
Classes
| Name | Description |
|---|---|
ConversionWarning | A part of a Matplotlib figure that has no Plotly counterpart here and is left out. |
Functions
| Name | Description |
|---|---|
animation_to_plotly | Convert a Matplotlib animation of the plotting functions into a Plotly figure with frames. |
bare | Strip a Plotly figure to its data, for a header picture or a front page. |
display_bundle | The notebook output of a Plotly figure: its JSON, an HTML copy and a text line. |
get_backend | Return the backend of plots that do not pass backend= themselves. |
get_math | Return how the formulas of labels reach Plotly figures. |
mathjax_source | "cdn" for a figure with a LaTeX label (see set_math()), else False. |
plotly_text | Turn a Matplotlib label into Plotly text. |
resolve_backend | The backend a plot draws with: backend, or the default if it is None. |
save_posters | Write pictures of a Plotly figure for a docs page, for light and dark mode. |
set_backend | Set the backend of every plot that does not pass backend= itself. |
set_math | Set how the formulas of labels (Matplotlib's $...$ mathtext) reach Plotly figures. |
to_plotly | Convert a drawn Matplotlib figure into an interactive Plotly figure. |
viewer_to_plotly | Convert a slider viewer into a Plotly figure with one slider. |
web_figure | A Plotly figure as a web figure, the format of maxplotlib.web. |
with_backend | Give an accessor plot method the backend option. |
BACKENDSattributemodule attribute#
BACKENDS = ('matplotlib', 'plotly', 'tikz')IMAGE_PIXELSattributemodule attribute#
IMAGE_PIXELS = 1200MATH_MODESattributemodule attribute#
MATH_MODES = ('unicode', 'latex')PAGE_PIXELSattributemodule attribute#
PAGE_PIXELS = 800PLOTLY_MIMEattributemodule attribute#
PLOTLY_MIME = 'application/vnd.plotly.v1+json'PX_PER_INCHattributemodule attribute#
PX_PER_INCH = 100.0PX_PER_PTattributemodule attribute#
PX_PER_PT = PX_PER_INCH / 72.0ConversionWarningclass#
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
| Name | Type | Default | Description |
|---|---|---|---|
animation | matplotlib.animation.FuncAnimation | required | The animation, e.g. from animate_slices(). |
labels | sequence of str | None | One slider label per frame. Default: the sweep values the animation was made for (for the animations of this package), else the frame numbers. |
prefix | str | None | Shown before the current label, e.g. "t = ". Default: the sweep’s name. |
play | bool | True | Add Play and Pause buttons. Default: True. |
strict | bool | False | Raise 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
| Name | Type | Description |
|---|---|---|
figure | plotly.graph_objects.Figure | The 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
Returns
tuple of dict- The MIME bundle and its metadata, as for
IPython.display.display(..., raw=True).
get_backendfunction#
def get_backend() -> strReturn the backend of plots that do not pass backend= themselves.
Returns
str"matplotlib"(the default),"plotly"or"tikz".
get_mathfunction#
def get_math() -> strReturn 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
| Name | Type | Description |
|---|---|---|
figure | plotly.graph_objects.Figure | The figure. |
plotly_textfunction#
def plotly_text(text, *, math: str | None = None) -> strTurn 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
| Name | Type | Default | Description |
|---|---|---|---|
text | str or None | required | The label. |
math | ('unicode', 'latex') | "unicode" | How formulas are written. Default: the mode of set_math(). |
Returns
str- The Plotly text;
""forNone.
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) -> strThe 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
| Name | Type | Default | Description |
|---|---|---|---|
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
| Name | Type | Default | Description |
|---|---|---|---|
figure | plotly.graph_objects.Figure | required | The figure. |
stem | str or pathlib.Path | required | The files’ path without the extension: <stem>.png and <stem>.dark.png. |
width | int | 800 | Width 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) -> strSet the backend of every plot that does not pass backend= itself.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
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
backendis 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) -> strSet 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
| Name | Type | Default | Description |
|---|---|---|---|
mode | ('unicode', 'latex') | "unicode" | The new mode. |
Returns
str- The previous mode, e.g. to restore it afterwards.
Raises
ValueError- If
modeis not"unicode"or"latex".
Examples
>>> plasma_plots.set_backend("plotly")>>> plasma_plots.set_math("latex") # e.g. in the first cell of a docs notebookto_plotlyfunction#
def to_plotly(figure, *, strict: bool = False)Convert a drawn Matplotlib figure into an interactive Plotly figure.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
figure | matplotlib.figure.Figure | required | A figure drawn by one of the plotting functions (or any figure with the artists they
use, see plasma_plots.plotly_backend). |
strict | bool | False | Raise 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
| Name | Type | Description |
|---|---|---|
viewer | plasma_plots.plotting.InteractiveSliceViewer | The 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) -> dictA 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
| Name | Type | Default | Description |
|---|---|---|---|
figure | plotly.graph_objects.Figure or dict | required | The 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
dictdata,layoutand, 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
| Name | Type | Description |
|---|---|---|
method | callable | A method returning a PlotResult, a FuncAnimation or an
InteractiveSliceViewer. |
Returns
callable- The method with the
backendoption.