Starlette

The starlette integration is typically imported as from mplbed import mplbed_starlette (although is also available as mplbed.integration.starlette).

To display a figure at a particular route

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

from mplbed import mplbed_starlette

@mplbed_starlette.figure_page
def figure(request):
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [4, 5, 6])
    return fig

app = mywebframework.App(...)
setup(app)

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

The above example sets up mplbed using the setup function which offers several options for customization:

mplbed.mplbed_starlette.setup(app, *, templates=None, do_install_middleware=True, prefix='/webagg', mplbed_starlette_app=None, mplbed_starlette_app_kwargs=None, manage_routing=True, do_register_context_processor=None, do_use_mpl_backend=True, use_webaggext_backend=True)

Setup the mplbed integration for the given Starlette app.

This function performs all the integration steps necessary to use mplbed with Starlette, including installing middleware, registering context processors, and configuring the matplotlib backend. The default parameter values are suitable for most use cases, but can be overridden as needed.

Parameters:
  • app (Starlette) – The Starlette app to integrate with mplbed.

  • templates (Jinja2Templates | None) – The Jinja2Templates instance to use for rendering templates. If None, no context processor will be registered. Default is None.

  • do_install_middleware (bool, optional) – Whether to install the mplbed middleware on the given app. Default is True.

  • prefix (str, optional) – The URL prefix for the routes handleded by mplbed. Default is ‘/webagg’.

  • mplbed_starlette_app (Starlette, optional) – The Starlette app to use for the mplbed routes, as returned by mplbed_starlette_app_factory. If not provided, a new app will be created using the provided mplbed_starlette_app_kwargs.

  • mplbed_starlette_app_kwargs (dict, optional) – Keyword arguments to pass to the Mplbed app factory if mplbed_starlette_app is not provided.

  • manage_routing (bool, optional) – Whether the ASGI middleware should manage routing. Default is True. If you set this to False, you are responsible for routing requests to the Mplbed app under the given prefix.

  • do_register_context_processor (bool, optional) – Whether to register the mplbed context processor on the given app. By default this will be true when the templates parameter is set to a Jinja2Templates instance.

  • do_use_mpl_backend (bool, optional) – Whether to setup the matplotlib backend for rendering figures. Default is True.

  • use_webaggext_backend (bool, optional) – Whether to use webaggext rather than the basic webagg backend for rendering figures. Default is True.

The figure_page helper is used as a decorator to wrap a route handler that returns a matplotlib figure. Other ways of using it are possible:

mplbed.mplbed_starlette.figure_page(inner=None, **figure_page_kwargs)

Decorator to create a Starlette Response object containing the HTML for the given figure using a function taking and returning raw strings.

This function can be called in three ways:

  1. As a decorator for a function taking any number of arguments and returning a matplotlib Figure object, making it appropriate to use as a decorator for view/handler function.

  2. As a decorator for a function taking no arguments and returning a matplotlib Figure object, making it appropriate to use as a decorator for a figure closure within a view/handler.

  3. As a decorator factory taking keyword arguments to pass through to the underlying function figure_standalone, e.g. @figure_page(template=...).

All usages are generic with regards to async/sync

Internally this decorator uses the function figure_standalone to generate the HTML and create the Starlette Response.

Example

Usage 1:

@figure_page
(async)  def my_handler(request):
    return Figure()

Usage 2:

(async)  def my_handler(request):
    # ...
    @figure_page
    (async)  def create_figure():
        return Figure()
    return (await)  create_figure()
Parameters:
  • prevent_default_navigation (bool, optional) – Prevent the browser’s default scrolling behavior for wheel, Arrow, PageUp/PageDown, Home/End, and Space events directed at the plot. Events are still sent to Matplotlib. Default is False.

  • template (callable, optional) – A callable taking the raw strings head, title and fig as keyword arguments and returning the HTML template to use for rendering the figure page as a raw string. Will default to default_figure_page_template if not provided.

Further examples

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)