Reputation: 1457
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.
Upvotes: 11
Views: 16898
Reputation: 990
Cleaning up the chart is not enough, you must also cleanup the data too.
This is how I plot my scatter chart:
function tracciaGrafico() {
data = [];
trace = [];
indexTrace = 0;
// Cleanup only if not first start (else it is already clean, and this would raise an error):
if (FirstStart) {
FirstStart = false;
} else { // Clear chart before plotting if it has already peing plotted.
Plotly.deleteTraces('myDiv', clearData);
clearData = [];
}
Squadre.forEach(function(squadra) {
trace[indexTrace] = puntiSquadraCumulativi[squadra]; // Copy trace data from my source array
data.push(
{
x: xArray,
y: puntiSquadraCumulativi[squadra],
type: "scatter",
name: squadra, // from "forEach"
line: {width: 5}
}
); // Add trace to data array
clearData.push(indexTrace); // Add trace index to array I will use to clean the old chart
indexTrace++;
});
Plotly.newPlot('myDiv', data); // Plot data
}
While building the chart I build an array (clearData) which then I can use to clear the chart: it just containing all the indexes of all the traces, and it is the argument of Plotly.deleteTraces('myDiv', clearData);
But maybe you actually don't want to delete traces but just update them:
https://plot.ly/javascript/plotlyjs-function-reference/#plotlyupdate
High performance way to update graph with new data in Plotly?
Upvotes: 0
Reputation: 5011
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.
Upvotes: 18
Reputation: 148
Newplot, Purge + newplot, react, and delete traces are all not working. There needs to be a better "clear" function supported directly from plotly
Upvotes: 0
Reputation: 449
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]);
}
Upvotes: 4