Updating matplotlib charts

The easiest way to update matplotlib charts is to first write a function that can generate a chart. The most common way to use matplotlib is to use syntax like plt.plot(...) followed by a plt.show(...) and the best way to capture all of these layers is to wrap them all ina single function. Once you have such a function, you can use the @refresh_matplotlib decorator to turn this function into something that we can use in a refreshable-chart.

The decorator takes the matplotlib image and turns it into a base64 encoded string that can be plotted by <img> tags in html. You can see this for yourself in the example below. The img(src=...) function call in mohtml is effectively a bit of syntactic sugar around <img src="...">.

[Image blocked: No description]

Having a static image is great, but we want dynamic images! That's where our ImageRefreshWidget comes in. It allows you to trigger a streaming update to an image by running code from another cell. Try it out below!

When you re-run the cell below you should see that the widget updates. This works because the widget knows how to respond to a change to the widget.src property. You only need to make sure that you pass along a base64 string that html images can handle, which is covered by the decorator that we applied earlier.

Updating altair charts

This library can also deal with altair charts. This works by turning the chart into an SVG. This is a static representation that does not require any javascript to run, which means that we can apply a similar pattern as before!

Due to a required dependency to convert the altair chart to SVG we cannot run the altair demo in WASM. This code will run just fine locally on your machine but currently breaks on the Github pages deployment.

Unlike matplotlib charts though, altair is actually designed to give you objects back. That means that you don't need to use a decorated function for the update, you can also just convert the altair chart to SVG directly. This library supports utilities for both patterns.

Oh ... one more thing about that HTMLRefreshWidget

We are injecting html now into that widget to allow us to draw altair charts. But why stop there? We can put in any HTML that we like!

Progress bars

We also provide progress bars that can update inplace without needing any 3rd party ipywidget tools. These should still work across all notebooks. These progress bars can also be updated from another cell in marimo, which the base progress bar does not allow.