@mddoc
def interactive(figure: Figure | SubFigure | Axes) -> Html:
"""Render a matplotlib figure using an interactive viewer.
The interactive viewer allows you to pan, zoom, and see plot coordinates
on mouse hover.
Example:
```python
plt.plot([1, 2])
# plt.gcf() gets the current figure
mo.mpl.interactive(plt.gcf())
```
Args:
figure (matplotlib Figure or Axes): A matplotlib `Figure` or `Axes` object.
Returns:
Html: An interactive matplotlib figure as an `Html` object.
"""
# No top-level imports of matplotlib, since it isn't a required
# dependency
from matplotlib.axes import Axes
if isinstance(figure, Axes):
maybe_figure = figure.get_figure()
assert maybe_figure is not None, "Axes object does not have a Figure"
figure = maybe_figure
ctx = get_context()
if not isinstance(ctx, KernelRuntimeContext):
return NonInteractiveMplHtml(figure)
# When virtual files are not supported (e.g., during HTML export),
# fall back to static PNG instead of interactive plot
if not ctx.virtual_files_supported:
return NonInteractiveMplHtml(figure)
# Figure::figure returns self; SubFigure::figure returns the parent Figure
is_subfigure = figure.figure is not figure
if is_subfigure:
warnings.warn(
message="SubFigure is not supported in interactive mode; "
"rendering as static PNG instead. "
"Consider using a regular Figure instead.",
stacklevel=2,
)
return NonInteractiveMplHtml(figure=figure)
from marimo._plugins.ui._impl.from_mpl_interactive import mpl_interactive
return mpl_interactive(figure)