Remove all traces from plotly.js plot

11,435

Solution 1

There's two ways of doing this, both listing in the plotlyjs function reference page.

Option 1 (tell plotly to delete the trace(s) in question):

Plotly.deleteTraces(graphDiv, 0);

where the second argument is the trace index of the trace to delete. Note that this second argument can also be an array of indices allowing you to delete multiple traces at once.

Option 2 (tell plotly to make a new plot with new data):

 Plotly.newPlot(graphDiv, data, layout);

where the arguments are the same as for Plotly.plot. This creates a new plot drawing only the data sent in the second argument. More precisely, Plotly.newPlot is idempotent whereas Plotly.plot isn't.

Solution 2

you can remove the last trace, and the previous one, and so one until the last one :

while(graphDiv.data.length>0)
{
      Plotly.deleteTraces(graphDiv, [0]);
}
Share:
11,435
Ian
Author by

Ian

R&D Engineer @ MIT

Updated on June 20, 2022

Comments

  • Ian
    Ian almost 2 years

    I have a page containing a plot.ly plot, that I want to write data to a few times, overwriting what was there before.

    I can't find a way to remove all traces from my plotly.js plot, and just replotting adds the data without removing the old.

  • Ian
    Ian over 8 years
    Thanks. I had seen deleteTraces, but I have a variable number of traces on the plot, so couldn't see an easy way to populate the trace index array. Also, I had tried newPlot in place of plot, but the traces are still being added, rather than replaced, and the plot title isn't updated. Does newPlot spawn a new plot, or remove all and add the new traces? Trying to work out what's going wrong
  • etpinard
    etpinard over 8 years
    Regarding newPlot, there was a bug with it that affected call signatures that use a string id as the first argument. The updated version will be pushed soon. We apologize for the inconvenience. In the meantime, `Plotly.newPlot(document.getElementById('plot-id'), data, layout) should work.
  • user2023861
    user2023861 about 5 years
    That link is dead
  • Michael Dausmann
    Michael Dausmann over 3 years
    Option 1 doesn't work.. only removes one trace. even if you remove all traces, still leaves titles etc. use option 2
  • Michael Dausmann
    Michael Dausmann over 3 years
    better but does not remove titles and axes etc.. use newPlot as above