fig_utils¶
Utilities for rendering matplotlib figures as HTML.
- neutcurve.fig_utils.fig_html(fig, display_method)[source]¶
Render a large matplotlib figure as a self-contained HTML string.
This function is designed for when you have a very large matplotlib figure (eg, as produced by the plotting functions of
neutcurve.curvefits.CurveFits) and you want to put it in an HTML page. Fordisplay_method="svg"and"pdf"the figure is placed in a fixed-height scrollable box, so that a figure with many panels does not force the rest of the page arbitrarily far down.The same figure always gives the same HTML, so a report built from this can be tracked in version control without every run showing a difference.
Requires pillow if you are using
display_method="png8"; it is installed with matplotlib in any case.- Args:
- fig (matplotlib.figure.Figure)
The figure we want to render.
- display_method {“svg”, “pdf”, “png8”}
Render the figure as a SVG, as a PDF, or as a PNG8. In general, rendering as a PNG8 will be the smallest size although also the lowest resolution.
- Returns:
- str
HTML that can be embedded in a page, or passed to
marimo.Html.
Example:
>>> import matplotlib.figure >>> fig = matplotlib.figure.Figure(figsize=(2, 2)) >>> _ = fig.subplots().plot([0, 1], [0, 1])
The SVG is wrapped in the scrollable box, and is a real SVG rather than an image:
>>> html = fig_html(fig, "svg") >>> '<div id="svgwrap" style="width:100%;height:80vh;overflow:auto">' in html True >>> "<svg" in html True
The other methods embed the figure as a data URI:
>>> fig_html(fig, "pdf").startswith("<iframe src='data:application/pdf;base64,") True >>> fig_html(fig, "png8").startswith('<img src="data:image/png;base64,') True
Rendering the same figure twice gives the same HTML:
>>> all(fig_html(fig, m) == fig_html(fig, m) for m in ["svg", "pdf", "png8"]) True
Anything else is an error. Note in particular that there is no
"inline"method here, as a bare figure has no HTML form; seeneutcurve.marimo_utils.display_fig_marimo()for that:>>> fig_html(fig, "inline") Traceback (most recent call last): ... ValueError: Invalid display_method='inline', valid methods are 'svg', 'pdf', 'png8'