Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Fix `mo.ui.matplotlib` ghosting when figure size changes (#8398)

Trevor Manzec05f44f60e2
diff --git a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts
index 2d2f5ccc25..b7fca724f2 100644
--- a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts
+++ b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts
@@ -330,10 +330,7 @@ export class MatplotlibRenderer {
const prev = this.#state;
this.#state = state;
- if (state.chartBase64 !== this.#currentChartBase64) {
- this.#loadImage(state.chartBase64);
- return;
- }
+ let needsRedraw = false;
// Update canvas dimensions if changed
if (state.width !== prev.width || state.height !== prev.height) {
@@ -342,15 +339,20 @@ export class MatplotlibRenderer {
this.#canvas.height = state.height * dpr;
this.#canvas.style.width = `${state.width}px`;
this.#canvas.style.height = `${state.height}px`;
+ needsRedraw = true;
+ }
+
+ if (state.chartBase64 !== this.#currentChartBase64) {
+ this.#loadImage(state.chartBase64);
+ return;
}
// Redraw if style props changed or dimensions changed
if (
+ needsRedraw ||
state.selectionColor !== prev.selectionColor ||
state.selectionOpacity !== prev.selectionOpacity ||
- state.strokeWidth !== prev.strokeWidth ||
- state.width !== prev.width ||
- state.height !== prev.height
+ state.strokeWidth !== prev.strokeWidth
) {
this.#drawCanvas();
}
@@ -364,6 +366,15 @@ export class MatplotlibRenderer {
// Clear selection on new chart
this.#interaction = { type: "idle" };
+ // Clear stale image so old content doesn't linger while new image loads
+ this.#image = null;
+ const ctx = this.#canvas.getContext("2d");
+ if (ctx) {
+ const dpr = globalThis.devicePixelRatio ?? 1;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, this.#state.width, this.#state.height);
+ }
+
const img = new Image();
img.onload = () => {
if (generation !== this.#imageGeneration) {