Examples index

All examples live under the examples/ directory. Run them with:

uv sync -U --all-groups --all-extras
cd examples && uv run python run_example.py

Or directly:

# Starlette (via daphne/uvicorn)
cd examples/starlette && uv run daphne -p 8000 draw_idle:app

# Quart
cd examples/quart && uv run python basic.py

# Django (via daphne)
cd examples/django && uv run daphne -p 8000 asgi:application

# NiceGUI
uv run python examples/nicegui/basic.py

NiceGUI

Install the optional integration with uv add "mplbed[nicegui]". Call setup(app) before ui.run(), then configure each element through its owned figure. Calling update() after changing an artist redraws the live WebAgg canvas without replacing the NiceGUI element.

Two live figures (basic.py)

Creates two client-owned figures, updates one independently, and demonstrates that standard NiceGUI classes and layout containers remain available. The /navigation page also compares normal embedding with matplotlib(prevent_default_navigation=True) for plots that consume wheel or navigation-key input.

"""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)

Starlette

Plot inside a toggled parent (display_none.py)

Demonstrates hiding and showing a scatter plot by toggling display: none on its parent element.

"""Hide and show a scatter plot by toggling ``display: none`` on its parent."""

from matplotlib.figure import Figure
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route

from mplbed import mplbed_starlette, raw_html


def homepage(request):
    """Render a scatter plot inside a parent with optional initial hiding."""
    fig = Figure()
    ax = fig.add_subplot()
    ax.scatter([1, 2, 3], [1, 4, 2], color="red", s=200)
    initially_hidden = "initially-hidden" in request.query_params
    hidden_after_init = "hidden-after-init" in request.query_params
    parent_style = ' style="display: none"' if initially_hidden else ""
    button_label = "Show plot" if initially_hidden or hidden_after_init else "Hide plot"
    hide_after_init = (
        '<script>document.getElementById("plot-parent").style.display = "none";</script>'
        if hidden_after_init
        else ""
    )

    return Response(
        f"""<!DOCTYPE html>
<html lang="en">
  <head>
    {raw_html.head_content()}
    <title>Toggle a plot</title>
  </head>
  <body>
    <button id="toggle-plot" type="button">{button_label}</button>
    <div id="plot-parent"{parent_style}>
      {raw_html.figure_html(fig)}
    </div>
    {hide_after_init}
    <script>
      const button = document.getElementById("toggle-plot");
      const parent = document.getElementById("plot-parent");
      button.addEventListener("click", () => {{
        const hidden = parent.style.display === "none";
        parent.style.display = hidden ? "block" : "none";
        button.textContent = hidden ? "Hide plot" : "Show plot";
      }});
    </script>
  </body>
</html>
""",
        media_type="text/html",
    )


app = Starlette(debug=True, routes=[Route("/", homepage)])
mplbed_starlette.setup(app)

Single standalone figure (draw_idle.py)

Demonstrates draw_idle with an interactive keyboard event: pressing Enter swaps the colors of two scatter plots.

"""
Shows draw_idle(...) working with webagg and webaggext --- pressing enter swaps the
colors of the two scatter plots.

Flags: USE_BASIC_WEBAGG_BACKEND
"""
import os
from matplotlib import pyplot as plt

from starlette.applications import Starlette
from starlette.routing import Route

from mplbed import mplbed_starlette


use_basic_webagg_backend = "USE_BASIC_WEBAGG_BACKEND" in os.environ


def page(request):
    fig, (ax1, ax2) = plt.subplots(nrows=2)

    x = [0, 1, 2]

    coll1 = ax1.scatter(x, x, c=["r", "g", "b"])
    coll2 = ax2.scatter(x, x, c=["b", "g", "r"])

    def accept(event):
        match event.key:
            case "enter":
                # swap facecolors
                fc1 = coll1.get_facecolors()
                fc2 = coll2.get_facecolors()
                coll1.set_facecolors(fc2)
                coll2.set_facecolors(fc1)
                fig.canvas.draw_idle()
            case _:
                pass

    fig.canvas.mpl_connect("key_press_event", accept)
    return mplbed_starlette.figure_standalone(fig)


app = Starlette(
    debug=True,
    routes=[Route('/', page)],
)
mplbed_starlette.setup(app, use_webaggext_backend=not use_basic_webagg_backend)

Two embedded figures (embed2_raw.py)

Embeds two figures side-by-side in a single page using raw string templates.

"""
Creates two embedded figures using raw string templates using Starlette/mplbed/string formatting.
"""
from matplotlib.figure import Figure

from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route

from mplbed import mplbed_starlette, raw_html


def homepage_template(*, head, fig1, fig2):
    return f"""<!DOCTYPE html>
<html lang="en">
  <head>
    {head}
    <title>matplotlib</title>
  </head>

  <body>
    <div style="display: flex">
      <div>
        <h2>Figure 1</h2>
        {fig1}
      </div>
      <div>
        <h2>Figure 2</h2>
        {fig2}
      </div>
    </div>
  </body>
</html>
"""


def create_figure():
    import numpy as np
    fig = Figure()
    ax = fig.add_subplot()
    t = np.arange(0.0, 3.0, 0.01)
    s = np.sin(2 * np.pi * t)
    ax.plot(t, s)
    return fig


def homepage(request):
    fig1 = create_figure()
    fig2 = create_figure()
    return Response(
        homepage_template(
            head=raw_html.head_content(),
            fig1=raw_html.figure_html(fig1),
            fig2=raw_html.figure_html(fig2),
        ),
        media_type='text/html'
    )


app = Starlette(
    debug=True,
    routes=[Route('/', homepage)],
)
mplbed_starlette.setup(app)

Manual routing (mount_app.py)

Shows how to manually create the mplbed Starlette sub-app and mount it at a custom prefix instead of using setup().

"""
Shows manual creation and routing of the `mplbed` Starlette app.
"""
from matplotlib.figure import Figure

from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route, Mount

from mplbed import raw_html, mplbed_starlette, mplbed_app_factory


def homepage_template(*, head, fig1):
    return f"""<!DOCTYPE html>
<html lang="en">
  <head>
    {head}
    <title>Sine wave plot</title>
  </head>

  <body>
    <h2>Sine wave plot</h2>
    {fig1}
  </body>
</html>
"""


def create_figure():
    import numpy as np
    fig = Figure()
    ax = fig.add_subplot()
    t = np.arange(0.0, 3.0, 0.01)
    s = np.sin(2 * np.pi * t)
    ax.plot(t, s)
    return fig


def homepage(request):
    fig1 = create_figure()
    return Response(
        homepage_template(
            head=raw_html.head_content(),
            fig1=raw_html.figure_html(fig1),
        ),
        media_type='text/html'
    )


mplbed_app = mplbed_app_factory()
MPLBED_PREFIX = "/mymplbedprefix"
app = Starlette(
    debug=True,
    routes=[Route('/', homepage), Mount(MPLBED_PREFIX, app=mplbed_app, name="webagg")],
)
mplbed_starlette.setup(app, prefix=MPLBED_PREFIX, mplbed_starlette_app=mplbed_app, manage_routing=False)

MNE integration (integrate_mne.py)

Embeds an interactive MNE raw-data plot in a Starlette page.

"""
Shows how an existing application can be integrated with mplbed. This example
uses MNE, an EEG/MNE library, to create a figure and then embeds it in a
Starlette application.
"""
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route

from mplbed import mplbed_starlette, raw_html

import mne


def homepage_template(*, head, fig):
    return f"""<!DOCTYPE html>
<html lang="en">
  <head>
    {head}
    <title>matplotlib</title>
  </head>

  <body>
    <div style="display: flex">
      <div>
        <h2>Figure</h2>
        {fig}
      </div>
    </div>
  </body>
</html>
"""


def homepage(request):
    sample_data_folder = mne.datasets.sample.data_path()
    sample_data_raw_file = (
        sample_data_folder / "MEG" / "sample" / "sample_audvis_filt-0-40_raw.fif"
    )
    raw = mne.io.read_raw_fif(sample_data_raw_file)
    fig = raw.plot(show=False)

    return Response(
        homepage_template(
            head=raw_html.head_content(),
            fig=raw_html.figure_html(fig, on_close="msg_disable")
        ),
        media_type='text/html'
    )


app = Starlette(
    debug=True,
    routes=[Route('/', homepage)],
)
mplbed_starlette.setup(app)

Quart

Inline, iframe, and popup figures (basic.py)

Shows three embedding styles in a single Quart/Jinja2 app: an inline figure, a figure loaded inside an <iframe>, and a figure that opens as a modal popup.

"""
Shows inline figures, external figures and popups using mplbed/Quart/jinja2.
"""

from quart import Quart, render_template
from mplbed import mplbed_quart
from mplbed import safe_html


app = Quart(__name__)
mplbed_quart.setup(app)


def mk_plot():
    import matplotlib.pyplot as plt
    import numpy as np

    t = np.arange(0.0, 2 * np.pi, 0.01)
    s = np.sin(t)

    fig, ax = plt.subplots()
    ax.plot(t, s)

    return fig


@app.route('/')
async def index():
    return await render_template(
        "index.html",
        inline_fig=safe_html.figure_html(mk_plot()),
        external_iframe=mplbed_quart.iframe_for("figure"),
        open_inline_popup=safe_html.figure_html(mk_plot(), target="modal")
    )


@app.route('/figure')
async def figure():
    return mplbed_quart.figure_standalone(mk_plot())


if __name__ == "__main__":
    import os
    app.run(debug=True, port=int(os.environ.get("PORT", 8000)))

The Jinja2 templates used by this example:

templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4" crossorigin="anonymous"></script>
    <title>{% block title %}{% endblock %}</title>
    {{ mplbed_head(False) }}
</head>
<body style="padding: 1em; font-family: sans-serif;">
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

templates/index.html

{% extends "base.html" %}

{% block title %}Home{% endblock %}
        
{% block content %}
    <h2 style="font-size: 2em;">Inline figure</h2>
    {{ inline_fig }}

    <hr style="margin: 5em 0;">

    <h2 style="font-size: 2em;">External iframe</h2>
    {{ external_iframe }}

    <hr style="margin: 5em 0;">

    <h2 style="font-size: 2em;">Open inline popup</h2>
    {{ open_inline_popup }}
{% endblock %}

Django

Inline, iframe, and popup figures (asgi.py + mysite/)

Runs a Django project under Daphne, following the Django + Daphne deployment docs. asgi.py wraps the Django ASGI application with the mplbed middleware, and mysite/views.py embeds figures inline, inside an <iframe>, and as a modal popup, as well as demonstrating the raw and Django-template figure page decorators. Django templates get the mplbed_head variable from the mplbed context processor registered in mysite/settings.py.

asgi.py

"""
Runs the mplbed/Django example under Daphne, following the Django
documentation on deploying with ASGI/Daphne:

https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/daphne/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

from mplbed import mplbed_django

application = mplbed_django.setup(get_asgi_application())

mysite/settings.py

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = "django-insecure-mplbed-demo"
DEBUG = True
ALLOWED_HOSTS = ["*"]

ROOT_URLCONF = "mysite.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "mysite" / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "mplbed.integration.django.context_processor",
            ],
        },
    },
]

mysite/urls.py

from django.urls import path

from mysite import views

urlpatterns = [
    path("", views.index),
    path("figure", views.figure, name="figure"),
    path("figure-dtl", views.figure_dtl, name="figure_dtl"),
]

mysite/views.py

"""
Shows inline figures, external figures and popups using mplbed/Django.
"""

from django.shortcuts import render

from mplbed import mplbed_django
from mplbed import safe_html


def mk_plot():
    import matplotlib.pyplot as plt
    import numpy as np

    t = np.arange(0.0, 2 * np.pi, 0.01)
    s = np.sin(t)

    fig, ax = plt.subplots()
    ax.plot(t, s)

    return fig


def index(request):
    return render(
        request,
        "index.html",
        {
            "inline_fig": safe_html.figure_html(mk_plot()),
            "external_iframe": mplbed_django.iframe_for("figure"),
            "open_inline_popup": safe_html.figure_html(mk_plot(), target="modal"),
        },
    )


@mplbed_django.figure_page
def figure(request):
    return mk_plot()


@mplbed_django.figure_page_dtl(template="figure.html")
def figure_dtl(request):
    return mk_plot()

The Django templates used by this example:

mysite/templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    {{ mplbed_head }}
</head>
<body style="padding: 1em; font-family: sans-serif;">
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

mysite/templates/index.html

{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block content %}
    <h2 style="font-size: 2em;">Inline figure</h2>
    {{ inline_fig }}

    <hr style="margin: 5em 0;">

    <h2 style="font-size: 2em;">External iframe</h2>
    {{ external_iframe }}

    <hr style="margin: 5em 0;">

    <h2 style="font-size: 2em;">Open inline popup</h2>
    {{ open_inline_popup }}
{% endblock %}

mysite/templates/figure.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Figure</title>
    {{ mplbed_head }}
</head>
<body>
    {{ fig }}
</body>
</html>