NiceGUI¶
TODO
Expand this guide with an explanation of the element lifecycle, client-owned figures, redraw behavior, and cleanup. The API reference and runnable example below document the currently supported interface.
Install the optional integration with uv add "mplbed[nicegui]". Call
setup(app) before creating a matplotlib element or starting NiceGUI with
ui.run().
Plots that use wheel or navigation-key input can opt out of the corresponding browser scrolling behavior:
plot = matplotlib(prevent_default_navigation=True)
This covers wheel, Arrow, PageUp/PageDown, Home/End, and Space events. Tab and non-navigation keys retain their normal browser behavior.
API reference¶
- mplbed.integration.nicegui.setup(app, *, prefix='/webagg', mplbed_starlette_app=None, mplbed_starlette_app_kwargs=None, manage_routing=True, do_use_mpl_backend=True, use_webaggext_backend=True)
Configure a NiceGUI app for interactive mplbed elements.
- Parameters:
app (
Any) – The NiceGUI application to configure beforeui.run().prefix (
str) – URL prefix used for mplbed’s routes.mplbed_starlette_app (
Any) – An optional pre-built mplbed Starlette sub-application.mplbed_starlette_app_kwargs (
dict[str,Any] |None) – Optional arguments used to create the mplbed Starlette application.manage_routing (
bool) – Whether mplbed should route requests underprefix.do_use_mpl_backend (
bool) – Whether to select mplbed’s Matplotlib backend.use_webaggext_backend (
bool) – Whether to select WebAggExt instead of Matplotlib’s base WebAgg backend.
- Return type:
None
- mplbed.integration.nicegui.matplotlib(*, prevent_default_navigation=False, **figure_kwargs)
Create an interactive Matplotlib element with an owned figure.
- Parameters:
prevent_default_navigation (
bool) – Whether to prevent browser scrolling for wheel, Arrow, PageUp/PageDown, Home/End, and Space events. Defaults toFalse.**figure_kwargs (
Any) – Keyword arguments forwarded tomatplotlib.figure.Figure.
- Returns:
The newly created NiceGUI element.
- Return type:
Matplotlib
- class mplbed.integration.nicegui.Matplotlib(*, prevent_default_navigation=False, **figure_kwargs)
Bases:
ElementEmbed an owned Matplotlib figure as an interactive NiceGUI element.
- Parameters:
prevent_default_navigation (
bool) – Whether to prevent browser scrolling for wheel, Arrow, PageUp/PageDown, Home/End, and Space events. Defaults toFalse.**figure_kwargs (
Any) – Keyword arguments forwarded tomatplotlib.figure.Figure.
- property figure: Figure
The Matplotlib figure owned by this element.
- update()
Schedule a redraw of the figure for connected clients.
- Return type:
None
- component: Component | None = JsComponent(key='691ace23ae81e7be091d979e9dd7e651/nicegui.js', name='nicegui', path=PosixPath('/tmp/tmpptzjf1_5/src/mplbed/integration/nicegui.js'))
- exposed_libraries: ClassVar[list[Library]] = []
Further examples¶
Two live figures (basic.py)¶
Creates two client-owned figures, updates one independently, and demonstrates
that standard NiceGUI classes and layout containers remain available. Its
/navigation page demonstrates opt-in browser navigation suppression.
"""Shows two independently updating interactive mplbed figures in NiceGUI."""
import os
from nicegui import app, ui
from mplbed.integration.nicegui import matplotlib, setup
setup(app)
@ui.page("/")
def index() -> None:
"""Create a fresh pair of figures for each NiceGUI client."""
with ui.row():
with ui.column():
first_plot = matplotlib(figsize=(4, 3)).classes("plot-one")
with first_plot.figure as first_figure:
first_axes = first_figure.subplots()
(first_line,) = first_axes.plot([1, 2, 3], [1, 2, 3])
def update_first() -> None:
first_line.set_ydata([3, 1, 2])
first_plot.update()
ui.button("Update first", on_click=update_first)
ui.button("Delete first", on_click=first_plot.delete)
with ui.column():
second_plot = matplotlib(figsize=(4, 3)).classes("plot-two")
with second_plot.figure as second_figure:
second_axes = second_figure.subplots()
second_axes.plot([1, 2, 3], [2, 3, 1])
def _navigation_plot(*, captured: bool, plot_class: str):
plot = matplotlib(
figsize=(4, 3),
prevent_default_navigation=captured,
).classes(plot_class)
axes = plot.figure.subplots()
axes.plot([1, 2, 3], [1, 2, 3])
event_count = 0
def update_on_input(event) -> None:
nonlocal event_count
event_count += 1
axes.set_title(f"Input events: {event_count}")
plot.update()
plot.figure.canvas.mpl_connect("key_press_event", update_on_input)
plot.figure.canvas.mpl_connect("scroll_event", update_on_input)
plot.update()
return plot
@ui.page("/navigation")
def navigation() -> None:
"""Compare normal page navigation with a plot that captures it."""
ui.html('<div style="height: 40rem">Scroll down to the plots.</div>')
with ui.row():
with ui.column():
ui.label("Browser navigation enabled")
_navigation_plot(captured=False, plot_class="navigation-default")
with ui.column():
ui.label("Browser navigation captured")
_navigation_plot(captured=True, plot_class="navigation-captured")
ui.html('<div style="height: 80rem">Page content after the plots.</div>')
if __name__ in {"__main__", "__mp_main__"}:
ui.run(host="127.0.0.1", port=int(os.environ.get("PORT", 8080)), reload=False, show=False)