MatplotlibChart
Displays a Matplotlib chart.
To display a Matplotlib figure with a built-in toolbar UI, use
MatplotlibChartWithToolbar.
This control requires the matplotlib
Python package to be installed.
See this installation guide for more information.
Inherits: GestureDetector
Properties
figure- Matplotlib figure to draw - an instance ofmatplotlib.figure.Figure.img_count- The sequence number of the next frame, starting at 1.
Events
on_message- The event is triggered on figure message update.on_toolbar_buttons_update- Triggers when toolbar buttons status is updated.
Methods
back- Goes back to the previous view.builddownload- Downloads the current figure in the specified format.forward- Goes forward to the next view.home- Resets the view to the original state.pan- Activates the pan tool.send_binary- Sends a binary message to the front end.send_json- Sends a JSON message to the front end.send_message- Sends a message to the figure's canvas manager.will_unmount- Called when the control is about to be removed from the page.zoom- Activates the zoom tool.
Examples
Bar Chart
Based on an official Matplotlib example.
import os
import sys
# Load Matplotlib's `ft2font` extension with RTLD_DEEPBIND, so it binds to the
# FreeType and harfbuzz it was built against.
#
# A packaged Linux app embeds Python in the Flutter process, where GTK has
# already loaded the system libfreetype/libharfbuzz into the global symbol
# namespace. `ft2font` statically links its own copies but also exports their
# symbols, so its internal calls resolve to the system ones instead. The ABI
# mismatch corrupts glyph metrics - a 10pt "-40" measures millions of points
# wide - and every text draw then fails with
# "FT_Render_Glyph ... error 0x62: raster overflow".
#
# Must run before Matplotlib is imported: the extension is cached after its
# first load. No-op wherever the flag is absent (macOS, Windows, Android, iOS,
# Pyodide) - none of those resolve symbols through a flat global namespace.
if hasattr(os, "RTLD_DEEPBIND"):
_dlopenflags = sys.getdlopenflags()
sys.setdlopenflags(_dlopenflags | os.RTLD_DEEPBIND)
try:
from matplotlib import ft2font # noqa: F401
finally:
sys.setdlopenflags(_dlopenflags)
import matplotlib.pyplot as plt
import flet as ft
import flet_charts as fch
def main(page: ft.Page):
fig, ax = plt.subplots()
fruits = ["apple", "blueberry", "cherry", "orange"]
counts = [40, 100, 30, 55]
bar_labels = ["red", "blue", "_red", "orange"]
bar_colors = ["tab:red", "tab:blue", "tab:red", "tab:orange"]
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel("fruit supply")
ax.set_title("Fruit supply by kind and color")
ax.legend(title="Fruit color")
page.add(
ft.SafeArea(
expand=True,
content=fch.MatplotlibChart(figure=fig, expand=True),
)
)
if __name__ == "__main__":
ft.run(main)

Declarative apps
In a component, create the figure once with use_memo and change it on each render: the chart redraws a figure that has changed since it was last drawn. A chart given another figure switches to it.
A figure created with plt.subplots() directly in the component's body is a new one on every render, which resets zoom and pan, and pyplot keeps each of them in memory until plt.close(figure). Close a figure the component no longer needs in the cleanup of a use_effect.
Declarative
The figure is created once with use_memo and changed on each render.
import os
import sys
# Load Matplotlib's `ft2font` extension with RTLD_DEEPBIND, so it binds to the
# FreeType and harfbuzz it was built against.
#
# A packaged Linux app embeds Python in the Flutter process, where GTK has
# already loaded the system libfreetype/libharfbuzz into the global symbol
# namespace. `ft2font` statically links its own copies but also exports their
# symbols, so its internal calls resolve to the system ones instead. The ABI
# mismatch corrupts glyph metrics - a 10pt "-40" measures millions of points
# wide - and every text draw then fails with
# "FT_Render_Glyph ... error 0x62: raster overflow".
#
# Must run before Matplotlib is imported: the extension is cached after its
# first load. No-op wherever the flag is absent (macOS, Windows, Android, iOS,
# Pyodide) - none of those resolve symbols through a flat global namespace.
if hasattr(os, "RTLD_DEEPBIND"):
_dlopenflags = sys.getdlopenflags()
sys.setdlopenflags(_dlopenflags | os.RTLD_DEEPBIND)
try:
from matplotlib import ft2font # noqa: F401
finally:
sys.setdlopenflags(_dlopenflags)
import matplotlib.pyplot as plt
import numpy as np
import flet as ft
import flet_charts as fch
X = np.linspace(0, 10, 500)
def create_figure():
figure, ax = plt.subplots()
ax.set(xlim=(0, 10), ylim=(-1.1, 1.1), xlabel="time", ylabel="amplitude")
ax.grid(alpha=0.3)
(line,) = ax.plot(X, np.zeros_like(X))
return figure, line
@ft.component
def App():
frequency, set_frequency = ft.use_state(1.0)
cosine, set_cosine = ft.use_state(False)
# Create the figure once and change it on each render: the chart redraws
# a figure that has changed, and keeps its zoom and pan.
figure, line = ft.use_memo(create_figure, [])
wave = np.cos if cosine else np.sin
line.set_ydata(wave(frequency * X))
line.axes.set_title(f"{wave.__name__}({frequency:.1f}x)")
return ft.SafeArea(
expand=True,
content=ft.Column(
controls=[
ft.Row(
controls=[
ft.Text("Frequency"),
ft.Slider(
expand=True,
min=0.5,
max=5,
divisions=45,
value=frequency,
on_change=lambda e: set_frequency(e.control.value),
),
ft.Switch(
label="Cosine",
value=cosine,
on_change=lambda e: set_cosine(e.control.value),
),
]
),
fch.MatplotlibChartWithToolbar(figure=figure, expand=True),
]
),
)
def main(page: ft.Page):
page.render(App)
if __name__ == "__main__":
ft.run(main)

To animate a figure, change it in an async use_effect and call figure.canvas.draw_idle() for each frame; the component isn't rendered again.
Declarative animation
An async use_effect changes the figure and asks the chart to redraw it, without rendering the component again.
import asyncio
import os
import sys
# Load Matplotlib's `ft2font` extension with RTLD_DEEPBIND, so it binds to the
# FreeType and harfbuzz it was built against.
#
# A packaged Linux app embeds Python in the Flutter process, where GTK has
# already loaded the system libfreetype/libharfbuzz into the global symbol
# namespace. `ft2font` statically links its own copies but also exports their
# symbols, so its internal calls resolve to the system ones instead. The ABI
# mismatch corrupts glyph metrics - a 10pt "-40" measures millions of points
# wide - and every text draw then fails with
# "FT_Render_Glyph ... error 0x62: raster overflow".
#
# Must run before Matplotlib is imported: the extension is cached after its
# first load. No-op wherever the flag is absent (macOS, Windows, Android, iOS,
# Pyodide) - none of those resolve symbols through a flat global namespace.
if hasattr(os, "RTLD_DEEPBIND"):
_dlopenflags = sys.getdlopenflags()
sys.setdlopenflags(_dlopenflags | os.RTLD_DEEPBIND)
try:
from matplotlib import ft2font # noqa: F401
finally:
sys.setdlopenflags(_dlopenflags)
import matplotlib.pyplot as plt
import numpy as np
import flet as ft
import flet_charts as fch
FRAME_INTERVAL = 1 / 30
X = np.linspace(0, 4 * np.pi, 400)
def create_figure():
figure, ax = plt.subplots()
ax.set(xlim=(X[0], X[-1]), ylim=(-2.2, 2.2), title="Interference of two waves")
ax.grid(alpha=0.3)
ax.plot(X, np.zeros_like(X), alpha=0.4, label="wave 1")
ax.plot(X, np.zeros_like(X), alpha=0.4, label="wave 2")
ax.plot(X, np.zeros_like(X), linewidth=2.5, label="sum")
ax.legend(loc="upper right")
return figure
def draw_waves(figure, time):
wave1 = np.sin(X - 2 * time)
wave2 = np.sin(1.5 * X + time)
for line, y in zip(figure.axes[0].lines, (wave1, wave2, wave1 + wave2)):
line.set_ydata(y)
figure.canvas.draw_idle()
@ft.component
def App():
playing, set_playing = ft.use_state(True)
speed, set_speed = ft.use_state(1.0)
figure = ft.use_memo(create_figure, [])
time = ft.use_ref(0.0)
# Each frame changes the figure and asks the chart to redraw it, without
# rendering the component again. The task is cancelled and started again
# when `playing` or `speed` changes, and cancelled on unmount.
async def animate():
while playing:
time.current += FRAME_INTERVAL * speed
draw_waves(figure, time.current)
await asyncio.sleep(FRAME_INTERVAL)
ft.use_effect(animate, [playing, speed])
return ft.SafeArea(
expand=True,
content=ft.Column(
controls=[
ft.Row(
controls=[
ft.IconButton(
icon=ft.Icons.PAUSE if playing else ft.Icons.PLAY_ARROW,
tooltip="Pause" if playing else "Play",
on_click=lambda: set_playing(lambda value: not value),
),
ft.Text(f"Speed: {speed:.1f}x"),
ft.Slider(
expand=True,
min=0.2,
max=3,
divisions=14,
value=speed,
on_change=lambda e: set_speed(e.control.value),
),
]
),
fch.MatplotlibChart(figure=figure, expand=True),
]
),
)
def main(page: ft.Page):
page.render(App)
if __name__ == "__main__":
ft.run(main)

Properties
figureclass-attributeinstance-attribute
figure: Figure = field(metadata={'skip': True})Matplotlib figure to draw - an instance of
matplotlib.figure.Figure.
Events
on_messageclass-attributeinstance-attribute
on_message: (
EventHandler[MatplotlibChartMessageEvent] | None
) = NoneThe event is triggered on figure message update.
on_toolbar_buttons_updateclass-attributeinstance-attribute
on_toolbar_buttons_update: (
EventHandler[
MatplotlibChartToolbarButtonsUpdateEvent
]
| None
) = NoneTriggers when toolbar buttons status is updated.
Methods
build
build()download
download(format) -> bytesDownloads the current figure in the specified format. Args: format (str): The format to download the figure in (e.g., 'png', 'jpg', 'svg', etc.). Returns: bytes: The figure image in the specified format as a byte array.