Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).

## Unreleased

### Fixed
- Resize `FigureWidget` charts in Jupyter when their container changes size, preserving explicit layout dimensions [[#5208](https://github.com/plotly/plotly.py/issues/5208)].

## [7.2.0] - 2026-11-24

Expand Down
93 changes: 37 additions & 56 deletions js/src/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -799,22 +799,23 @@ const serializers: Record<string, Serializer> = {
*/
export class FigureView {
viewID: string;
resizeEventListener: () => void;
private resizeObserver?: ResizeObserver;
private viewSize?: DOMRectReadOnly;

model: FigureModel;
el: HTMLElement;

constructor(model: FigureModel, el: HTMLElement) {
this.model = model;
this.el = el;
this.resizeObserver = new ResizeObserver(([entry]) => {
this.viewSize = entry.contentRect;
this.autosizeFigure();
});
}

/**
* The perform_render method is called by processLuminoMessage
* after the widget's DOM element has been attached to the notebook
* output cell. This happens after the initialize of the
* FigureModel, and it won't happen at all if the Python FigureWidget
* is never displayed in a notebook output cell
* Render the figure when anywidget creates a view.
*/
perform_render() {
var that = this;
Expand Down Expand Up @@ -857,6 +858,8 @@ export class FigureView {

Plotly.newPlot(that.el, initialTraces, initialLayout, config).then(
function () {
if (!that.resizeObserver) return;

// ### Send trace deltas ###
// We create an array of deltas corresponding to the new
// traces.
Expand Down Expand Up @@ -894,6 +897,8 @@ export class FigureView {
that.handle_plotly_doubleclick(update);
});

that.resizeObserver?.observe(that.el);

// Emit event indicating that the widget has finished
// rendering
var event = new CustomEvent("plotlywidget-after-render", {
Expand All @@ -906,64 +911,40 @@ export class FigureView {
);
}

/**
* Respond to Lumino events
*/
_processLuminoMessage(msg: any, _super: any) {
_super.apply(this, arguments);
var that = this;
switch (msg.type) {
case "before-attach":
// Render an initial empty figure. This establishes with
// the page that the element will not be empty, avoiding
// some occasions where the dynamic sizing behavior leads
// to collapsed figure dimensions.
var axisHidden = {
showgrid: false,
showline: false,
tickvals: [] as any[],
};

Plotly.newPlot(that.el, [], {
xaxis: axisHidden,
yaxis: axisHidden,
});
this.resizeEventListener = () => {
this.autosizeFigure();
}
window.addEventListener("resize", this.resizeEventListener);
break;
case "after-attach":
// Rendering actual figure in the after-attach event allows
// Plotly.js to size the figure to fill the available element
this.perform_render();
break;
case "after-show":
case "resize":
this.autosizeFigure();
break;
private autosizeFigure(layoutUpdate?: Partial<Plotly.Layout>) {
if (!this.viewSize) return;
if (layoutUpdate && !["width", "height", "autosize"].some(key => key in layoutUpdate)) {
return;
}
}

autosizeFigure() {
var that = this;
var layout = that.model.get("_widget_layout");
if (_.isNil(layout) || _.isNil(layout.width)) {
// @ts-ignore
Plotly.Plots.resize(that.el).then(function () {
var layout_edit_id = that.model.get("_last_layout_edit_id");
that._sendLayoutDelta(layout_edit_id);
});
const { width, height } = this.viewSize;
const layout = this.model.get("_widget_layout");
if (!width || !height || layout.autosize === false || (layout.width && layout.height)) {
return;
}
const graph = this.el as Plotly.PlotlyHTMLElement & {
autoplay?: boolean;
changed?: boolean;
};
const size = { width: layout.width ?? width, height: layout.height ?? height };
if (graph.layout.width === size.width && graph.layout.height === size.height) return;

// A view resize must not change the shared model or enter the plot's undo history.
const changed = graph.changed;
graph.autoplay = true;
const update = { ...size, autosize: true, _doNotReportToPy: true };
Plotly.relayout(graph, update);
graph.changed = changed;
}

/**
* Purge Plotly.js data structures from the notebook output display
* element when the view is destroyed
*/
remove() {
this.resizeObserver?.disconnect();
this.resizeObserver = undefined;
this.viewSize = undefined;
Plotly.purge(this.el);
window.removeEventListener("resize", this.resizeEventListener);
}

/**
Expand Down Expand Up @@ -1419,7 +1400,7 @@ export class FigureView {
if (msgData.source_view_id !== this.viewID) {
var relayoutData = msgData.relayout_data;
relayoutData["_doNotReportToPy"] = true;
Plotly.relayout(this.el, msgData.relayout_data);
Plotly.relayout(this.el, relayoutData).then(() => this.autosizeFigure(relayoutData));
}

// ### Send layout delta ###
Expand All @@ -1443,7 +1424,7 @@ export class FigureView {
);

style["_doNotReportToPy"] = true;
Plotly.update(this.el, style, layout, traceIndexes);
Plotly.update(this.el, style, layout, traceIndexes).then(() => this.autosizeFigure(layout));

// ### Send trace deltas ###
// We create an array of deltas corresponding to the updated
Expand Down
72 changes: 36 additions & 36 deletions plotly/package_data/widgetbundle.js

Large diffs are not rendered by default.

94 changes: 94 additions & 0 deletions tests/test_optional/test_figurewidget_resize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import asyncio
import json

from choreographer import Browser
import plotly.graph_objects as go


def test_figurewidget_resizes_with_its_container():
fig = go.FigureWidget(data=[go.Scatter(y=[1, 2])], layout_template="none")
state = fig.get_state(
key=[
"_widget_data",
"_widget_layout",
"_config",
"_last_layout_edit_id",
"_last_trace_edit_id",
]
)
script = """
async (moduleSource, state) => {
const url = URL.createObjectURL(new Blob([moduleSource], { type: 'text/javascript' }));
const { default: createWidget } = await import(url);
URL.revokeObjectURL(url);
const container = document.body.appendChild(document.createElement('div'));
container.style.cssText = 'width: 420px; height: 310px';
const chart = container.appendChild(document.createElement('div'));
chart.style.cssText = 'width: 100%; height: 100%';
const widget = createWidget();
const events = new EventTarget();
const writes = [];
widget.initialize({ model: {
get(key) { return state[key]; },
set(key, value) { writes.push(key); state[key] = value; },
on(event, callback) { events.addEventListener(event, callback); },
save_changes() {}
} });
const rendered = new Promise(resolve =>
document.addEventListener('plotlywidget-after-render', resolve, { once: true }));
const remove = widget.render({ el: chart });
await rendered;

function setContainerSize(width, height) {
container.style.width = width + 'px';
container.style.height = height + 'px';
}
function send(key, value) {
state[key] = value;
events.dispatchEvent(new Event('change:' + key));
}
async function svgSize(width, height) {
const deadline = performance.now() + 1500;
while (true) {
await new Promise(requestAnimationFrame);
const svg = chart.querySelector('svg.main-svg');
const w = Number(svg.getAttribute('width')), h = Number(svg.getAttribute('height'));
if ((w === width && h === height) ||
performance.now() >= deadline) return [w, h];
}
}
const initial = await svgSize(420, 310);
writes.length = 0;
setContainerSize(315, 255);
const narrow = await svgSize(315, 255);
const resizeWrites = writes.slice();
const undos = chart.undoQueue?.index ?? 0;
send('_py2js_update', {
style_data: {}, style_traces: [], layout_data: {height: 230},
trace_edit_id: 1, layout_edit_id: 1
});
setContainerSize(480, 355);
const fixedHeight = await svgSize(480, 230);
send('_py2js_relayout', {relayout_data: {height: null}, layout_edit_id: 2});
const clearedHeight = await svgSize(480, 355);
remove();
return [initial, narrow, resizeWrites, undos, fixedHeight, clearedHeight];
}
"""

async def run():
async with Browser() as browser:
tab = await browser.create_tab()
response = await tab.send_command(
"Runtime.evaluate",
{
"expression": f"({script})(...{json.dumps([fig._esm, state])})",
"awaitPromise": True,
"returnByValue": True,
},
)
result = response["result"]
assert "exceptionDetails" not in result, result.get("exceptionDetails")
return result["result"]["value"]

assert asyncio.run(run()) == [[420, 310], [315, 255], [], 0, [480, 230], [480, 355]]