“清理”和“更新”是以不同方式管理的不同事物。
如果您真的不想删除跟踪而只是更新它们,那么已经有一些问题了:
Plotly update data
High performance way to update graph with new data in Plotly?
如果您确实想删除跟踪,则必须同时删除/更新数据和图表。
这就是我绘制散点图的方式:
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
}
在构建图表时,我构建了一个数组 (clearData),然后我可以使用它来清除图表:它只包含所有轨迹的所有索引,它是 Plotly.deleteTraces('myDiv', clearData );
值得注意的是,您还可以使用 Javascript 的 findIndex() 函数访问单个跟踪:
data = [
{
line: {width: 5}
name: "myName1"
type: "scatter"
visible: "legendonly" // Plot trace but hide it to the user
x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y: [10, 11, 2, 23, 14, 5, 16, 7, 18, 29, 10]
},
{
line: {width: 5}
name: "myName2"
type: "scatter"
visible: "legendonly" // Plot trace but hide it to the user
x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y: [10, 1, 12, 13, 4, 25, 16, 17, 8, 19, 20]
}
];
allTraces=document.getElementById("myDiv").data; // Get data from chart AFTER plotting it.
// Find index of trace-object with "name" property = "text to find":
result = allTraces.findIndex(obj => {
return obj.name === "text to find";
}
// Make specified trace visible to user:
Plotly.restyle(document.getElementById("myDiv"), {"visible": true}, [result]);