MatPlotLibPlot
Group: Media
Description
MatPlotLibPlot puts a chart on your page. You draw the chart with
the matplotlib library's usual commands (plt.plot, plt.bar, and
so on), then place MatPlotLibPlot() in the page where the picture
should appear. The component captures whatever figure matplotlib
currently has open and embeds it as an image.
Syntax
MatPlotLibPlot()
MatPlotLibPlot(extra_matplotlib_settings)
Parameters
| Parameter | Type | Default | Meaning |
|---|---|---|---|
extra_matplotlib_settings |
dict |
{} |
Settings passed to matplotlib when saving the figure, like {"format": "svg"}. The format must be "png" (the default) or "svg". |
close_automatically |
bool |
True |
Close the figure as soon as the component is created, so the next chart starts fresh. |
Examples
Draw first, then place the component:
from drafter import *
from dataclasses import dataclass
import matplotlib.pyplot as plt
@dataclass
class State:
pass
@route
def index(state: State) -> Page:
plt.plot([12, 15, 11, 18, 16, 20])
plt.title("Treats eaten by Ada this week")
return Page(state, [
Header("Treat Tracker"),
MatPlotLibPlot()
])
start_server(State())
The chart can be driven by state, so it changes as the data does:
from drafter import *
from dataclasses import dataclass
import matplotlib.pyplot as plt
@dataclass
class State:
naps: list[int]
@route
def index(state: State) -> Page:
plt.bar(range(len(state.naps)), state.naps)
plt.title("Captain's naps per day")
return Page(state, [
Header("Nap Chart"),
MatPlotLibPlot(),
Button("Record a lazy day", "lazy_day")
])
@route
def lazy_day(state: State) -> Page:
state.naps.append(state.naps[-1] + 1)
return index(state)
start_server(State([3, 4, 2]))
Notes
- The component takes the figure that is open at the moment you
create it, so run your
plt.commands first and writeMatPlotLibPlot()after them. Commands that run after the component is created belong to the next chart. - Leave out
plt.show(). On your own computer it opens the chart in a separate window, and when your first page draws a chart the site does not start until you close that window. In the browser it does nothing. If a library calls it for you, see Libraries that draw their own charts. - Charts drawn in unit tests never leak into your pages: each
MatPlotLibPlot()keeps its own figure, even when the page is only compared and never shown. - The first page that uses matplotlib in the browser takes a while to appear: the library is downloaded and installed on demand. Later pages reuse it.
- By default the figure closes when the component is created. If
you draw one figure and show it twice on the same page, pass
close_automatically=Falseto the firstMatPlotLibPlot. - The chart is a picture: visitors cannot hover or zoom it.
- To store a chart in state or offer it as a download, call the
component's
to_picture()method to get a Picture value.