✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐍Plotly, Coiled CEOs Discuss Partnering & ML Experts show us how Dash + Dask apps work Register for the Webinar.

[Resolved] Passing generated plotly SVG between JS Events

Hey Everyone,

I’m creating a JS page that uses several Plotly graphs.
This is what I’d like to do ideally:

  1. Press a button (separated from the individual plots)
  2. Grab the SVG, or the put together in the toImage function
  3. Pass data through a JS function
  4. Replot in a new location

I’ve tried
Plotly.plot(id, data, layout, {displayModeBar: false})
.then(function (gd) {
Plotly.toImage(gd, download_format);
});

I can plot each individual graph, but I can’t get this function to pass its information. I’ve tried assigning variables to the Plotly.toImage() and to the Plotly.plot() functions.

Any ideas how to accomplish this?

Plotly.toImage returns a promise too.

var result;

Plotly.plot(id, data, layout, {displayModeBar: false})
.then(function (gd) {
Plotly.toImage(gd, download_format).then(function(imgData) { result = imgData });
});

should do the trick.

Thanks, etienne. It does make sense that toImage returns another promise.

I just tried your suggestion, but when I check result’s value outside of the promise nothing is defined.

var result;

Plotly.plot(id, data, layout, {displayModeBar: false})
.then(function (gd) {
Plotly.toImage(gd, download_format).then(function (imgData) {
result = imgData;
console.log('result_in: ', result);});
});
console.log('result_out: ', result);

the result_in will log the data, but the result_out will be undefined.

Yep, that’s because toImage is async. It completes after that 2nd console.log is executed.

Ah, I see.
I’m not too familiar with asynchronous calls. How would I delay, for example, the result_out console.log until after result is assigned imgData?

In case somebody else is as new to this as I was: JavaScript Async