Skip to content

Commit 534242e

Browse files
authored
Fix dashboard showing spurious matplotlib repr text next to figures (#14645)
Dashboards run Jupyter with ipynb-shell-interactivity: all, so every top-level expression echoes its value. matplotlib/pandas plotting calls return objects (plt.title() a Text, plt.boxplot() a dict of Line2D) whose text/plain repr leaked into rendered output beside the figure. HTML output showed a milder version under last_expr. The discard heuristic in isDiscardableTextExecuteResult (src/core/ jupyter/jupyter.ts) only caught single-line bracket-wrapped reprs and a few library prefixes. It missed Text(...) (no leading bracket), the multi-line dict from boxplot()/hist(), and single-line dicts short enough for IPython to keep on one line. - Discard Text(...) only when it leads with matplotlib's numeric coordinate signature (Text(0.5, ...)), not any Text(...) repr - Discard multi-line output only when it references a matplotlib object, leaving ordinary multi-line reprs untouched - Discard single-line {...} dicts the same way, for artifact dicts short enough to stay on one line Guarded by unit tests on the heuristic plus a dashboard+HTML smoke-all regression test. Fixes #11150
1 parent e22b5ed commit 534242e

5 files changed

Lines changed: 239 additions & 3 deletions

File tree

‎news/changelog-1.10.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ All changes included in 1.10:
8989

9090
### Jupyter
9191

92+
- ([#11150](https://github.com/quarto-dev/quarto-cli/issues/11150)): Fix `dashboard` format showing spurious intermediate text output (e.g. a `Text(...)` repr or a matplotlib object repr) next to a figure when a cell's top-level plotting calls echo their return values.
9293
- ([#13582](https://github.com/quarto-dev/quarto-cli/pull/13582)): Fix `application/pdf` and `text/latex` MIME types not being preferred over `image/svg+xml` when rendering Jupyter notebooks to PDF, which caused errors when `rsvg-convert` was not available. (author: @jkrumbiegel)
9394
- ([#14374](https://github.com/quarto-dev/quarto-cli/pull/14374)): Avoid a crash when a third-party Jupyter kernel (observed with Maple 2025, built on XEUS) returns `execute_reply` without the required `status` field. The failing cell is recorded as an error instead of aborting the render. (author: @ChrisJefferson)
9495

‎src/core/jupyter/jupyter.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1757,7 +1757,7 @@ async function mdFromCodeCell(
17571757
return md;
17581758
}
17591759

1760-
function isDiscardableTextExecuteResult(
1760+
export function isDiscardableTextExecuteResult(
17611761
output: JupyterOutput,
17621762
haveImage: boolean,
17631763
) {
@@ -1766,8 +1766,23 @@ function isDiscardableTextExecuteResult(
17661766
if (Object.keys(data).length === 1) {
17671767
const textPlain = data?.[kTextPlain] as string[] | undefined;
17681768
if (textPlain && textPlain.length) {
1769-
if (haveImage && textPlain.length === 1) {
1770-
return /^([<(\[]).*?([>)\]])$/.test(textPlain[0].trim());
1769+
if (haveImage) {
1770+
if (textPlain.length === 1) {
1771+
// single-line object reprs echoed next to the figure: <...>/(...)/[...]
1772+
// wrappers (Axes, Line2D, tuples) plus matplotlib Text from
1773+
// title()/xlabel()/ylabel()/set_title() — whose repr leads with a
1774+
// numeric coordinate (Text(0.5, ...)), unlike other libraries' Text
1775+
const first = textPlain[0].trim();
1776+
return /^([<(\[]).*?([>)\]])$/.test(first) ||
1777+
/^Text\([-\d]/.test(first) ||
1778+
(first.startsWith("{") && first.includes("<matplotlib."));
1779+
} else {
1780+
// multi-line reprs that are collections of matplotlib artists, e.g.
1781+
// the dict of Line2D returned by boxplot(). Only suppress when a
1782+
// matplotlib object is referenced, leaving ordinary multi-line
1783+
// output (lists, tuples, custom reprs) untouched
1784+
return textPlain.some((line) => line.includes("<matplotlib."));
1785+
}
17711786
} else {
17721787
return [
17731788
"[<matplotlib",
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/.quarto/
2+
**/*.quarto_ipynb
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
title: "Intermediate matplotlib output shown in dashboard (#11150)"
3+
format:
4+
html: default
5+
dashboard: default
6+
engine: jupyter
7+
echo: true
8+
_quarto:
9+
tests:
10+
dashboard:
11+
ensureHtmlElements:
12+
- ['img'] # the matplotlib figure is still rendered
13+
ensureHtmlElementCount:
14+
selectors: ['table', '.plotly-graph-div', '.cell-output-display pre']
15+
counts: [1, 1, 0] # table + graph both survive in one card (all); zero spurious text-output reprs
16+
html:
17+
ensureHtmlElements:
18+
- ['img'] # the matplotlib figure is still rendered
19+
ensureHtmlElementCount:
20+
selectors: ['table', '.plotly-graph-div', '.cell-output-display pre']
21+
counts: [0, 1, 0] # last_expr drops the table; one graph; zero spurious text-output reprs
22+
---
23+
24+
Dashboard format runs the Jupyter kernel with
25+
`ipynb-shell-interactivity: all`, so every top-level expression statement in a
26+
cell echoes its value, not just the last one. matplotlib/pandas/seaborn
27+
plotting calls return objects (`plt.title()` returns a `Text`, `plt.boxplot()`
28+
returns a dict of `Line2D`), and those object reprs leaked into the rendered
29+
output as spurious intermediate text next to the figure — the difference from
30+
HTML that #11150 reported. HTML is affected too, just less: under the default
31+
`last_expr` it only echoes the final expression's repr (`Text(...)`).
32+
33+
The first cell exercises the bug: it must render the figure but must not show
34+
the `Text(...)` or boxplot-dict reprs, in either format. The second cell guards
35+
the intentional multi-output capability that `shell-interactivity: all` gives
36+
dashboards. In a dashboard one cell becomes one card, so composing a card that
37+
holds both a summary table and a plot requires emitting both from a single
38+
cell. Under `all` both survive in that one card; under HTML's `last_expr` only
39+
the last expression (the graph) is kept and the table is dropped.
40+
41+
```{python}
42+
#| title: plot with a title
43+
import matplotlib.pyplot as plt
44+
x = [1, 2, 3, 4, 5, 10]
45+
plt.boxplot(x)
46+
plt.title("Test")
47+
```
48+
49+
```{python}
50+
#| title: table and graph in one card
51+
#| echo: false
52+
#| layout-ncol: 2
53+
import plotly.express as px
54+
df = px.data.tips()
55+
df.groupby("day", observed=True)["total_bill"].mean().reset_index()
56+
px.box(df, x="day", y="total_bill")
57+
```
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
/*
2+
* discardable-text.test.ts
3+
*
4+
* Copyright (C) 2026 Posit Software, PBC
5+
*/
6+
7+
import { unitTest } from "../../test.ts";
8+
import { assertEquals } from "testing/asserts";
9+
import { isDiscardableTextExecuteResult } from "../../../src/core/jupyter/jupyter.ts";
10+
import { kTextPlain } from "../../../src/core/mime.ts";
11+
import { JupyterOutput } from "../../../src/core/jupyter/types.ts";
12+
13+
// An execute_result whose only mime bundle is text/plain, stored as the
14+
// per-line array Jupyter emits.
15+
const execResult = (textPlainLines: string[]): JupyterOutput => ({
16+
output_type: "execute_result",
17+
data: { [kTextPlain]: textPlainLines },
18+
});
19+
20+
// text/plain reprs that top-level plotting expressions echo under
21+
// ipynb-shell-interactivity: all. The matplotlib reprs below are captured
22+
// verbatim from the executed 11150.quarto_ipynb (keep-ipynb: true) — Jupyter
23+
// emits text/plain as a per-line array, so multi-line reprs have length > 1.
24+
const boxplotDict = [
25+
"{'whiskers': [<matplotlib.lines.Line2D at 0x17685b54980>,\n",
26+
" <matplotlib.lines.Line2D at 0x17685b54ad0>],\n",
27+
" 'caps': [<matplotlib.lines.Line2D at 0x17685b54c20>,\n",
28+
" <matplotlib.lines.Line2D at 0x17685b54d70>],\n",
29+
" 'boxes': [<matplotlib.lines.Line2D at 0x17685b54830>],\n",
30+
" 'medians': [<matplotlib.lines.Line2D at 0x17685b54ec0>],\n",
31+
" 'fliers': [<matplotlib.lines.Line2D at 0x17685b55010>],\n",
32+
" 'means': []}",
33+
];
34+
// A single-line dict of matplotlib artists (small enough that IPython does not
35+
// pretty-print it across lines). Unambiguous plotting noise.
36+
const singleLineDict = ["{'line': <matplotlib.lines.Line2D at 0x1407>}"];
37+
const titleText = ["Text(0.5, 1.0, 'Test')"];
38+
const axesRepr = ["<Axes: title={'center': 'Test'}>"];
39+
const line2DRepr = ["<matplotlib.lines.Line2D at 0x14071bc7e00>"];
40+
// A DataFrame echoed alongside the figure: multi-line text/plain plus text/html
41+
// (also captured from 11150.quarto_ipynb). Two mime keys -> must be kept.
42+
const dataFrameText = [
43+
" day total_bill\n",
44+
"0 Fri 17.151579\n",
45+
"1 Sat 20.441379\n",
46+
"2 Sun 21.410000\n",
47+
"3 Thur 17.682742",
48+
];
49+
50+
unitTest(
51+
"jupyter - isDiscardableTextExecuteResult drops plotting-call reprs only alongside an image",
52+
// deno-lint-ignore require-await
53+
async () => {
54+
// Discard plotting-object noise when the cell also emitted an image.
55+
assertEquals(
56+
isDiscardableTextExecuteResult(execResult(titleText), true),
57+
true,
58+
"plt.title()/set_title() Text repr should be discarded",
59+
);
60+
assertEquals(
61+
isDiscardableTextExecuteResult(execResult(boxplotDict), true),
62+
true,
63+
"plt.boxplot() multi-line dict of Line2D should be discarded",
64+
);
65+
assertEquals(
66+
isDiscardableTextExecuteResult(execResult(axesRepr), true),
67+
true,
68+
"seaborn/pandas Axes repr should be discarded",
69+
);
70+
assertEquals(
71+
isDiscardableTextExecuteResult(execResult(line2DRepr), true),
72+
true,
73+
"bare Line2D repr should be discarded",
74+
);
75+
assertEquals(
76+
isDiscardableTextExecuteResult(execResult(singleLineDict), true),
77+
true,
78+
"single-line dict of matplotlib artists should be discarded",
79+
);
80+
81+
// Gate: with no image in the cell, nothing here is discarded — a cell
82+
// that only echoed these values (no figure) must keep them.
83+
assertEquals(
84+
isDiscardableTextExecuteResult(execResult(titleText), false),
85+
false,
86+
"Text repr must be kept when the cell has no image",
87+
);
88+
assertEquals(
89+
isDiscardableTextExecuteResult(execResult(boxplotDict), false),
90+
false,
91+
"boxplot dict must be kept when the cell has no image",
92+
);
93+
94+
// No over-suppression: legitimate output survives even alongside an image.
95+
// A Name(...) repr that is not a matplotlib Text must not be swept up.
96+
assertEquals(
97+
isDiscardableTextExecuteResult(
98+
execResult(["datetime.datetime(2020, 1, 1, 0, 0)"]),
99+
true,
100+
),
101+
false,
102+
"non-matplotlib single-line Name(...) repr must be kept",
103+
);
104+
// A non-matplotlib Text( repr (e.g. rich.text.Text -> Text('...')) has no
105+
// leading coordinate, so it must be kept.
106+
assertEquals(
107+
isDiscardableTextExecuteResult(execResult(["Text('hello world')"]), true),
108+
false,
109+
"non-matplotlib Text('...') repr must be kept",
110+
);
111+
// A multi-line bracketed value (list/tuple) with no matplotlib reference
112+
// must survive — the discard heuristic must not widen to arbitrary brackets.
113+
assertEquals(
114+
isDiscardableTextExecuteResult(
115+
execResult(["[1, 2, 3,\n", " 4, 5, 6]"]),
116+
true,
117+
),
118+
false,
119+
"multi-line list with no matplotlib reference must be kept",
120+
);
121+
// An arbitrary multi-line repr with no matplotlib reference must survive.
122+
assertEquals(
123+
isDiscardableTextExecuteResult(
124+
execResult(["MyResult(\n", " value=42,\n", ")"]),
125+
true,
126+
),
127+
false,
128+
"multi-line custom repr with no matplotlib reference must be kept",
129+
);
130+
// Multiple mime types (e.g. a DataFrame's text/plain + text/html) -> keep.
131+
assertEquals(
132+
isDiscardableTextExecuteResult(
133+
{
134+
output_type: "execute_result",
135+
data: { [kTextPlain]: dataFrameText, "text/html": ["<table>"] },
136+
},
137+
true,
138+
),
139+
false,
140+
"multi-mime output (DataFrame text/plain + text/html) must be kept",
141+
);
142+
143+
// Only execute_result is ever discardable.
144+
assertEquals(
145+
isDiscardableTextExecuteResult(
146+
{ output_type: "display_data", data: { [kTextPlain]: titleText } },
147+
true,
148+
),
149+
false,
150+
"display_data must never be discarded",
151+
);
152+
assertEquals(
153+
isDiscardableTextExecuteResult(
154+
{ output_type: "stream", name: "stdout", text: titleText },
155+
true,
156+
),
157+
false,
158+
"stream output must never be discarded",
159+
);
160+
},
161+
);

0 commit comments

Comments
 (0)