首先,我认为重用现有的绘图而不是创建新绘图会更有效。这是我的用例,根据用户输入,将一些迹线添加到绘图中。当用户输入更改时,我需要更改相同迹线上的点。
目前,我正在删除跟踪并创建新的图,但理想情况下,我想重用现有的跟踪清除数据。这可能吗?
答案 0 :(得分:0)
您可以使用deleteTraces
,然后使用addTraces
。或者,您可以直接在现有跟踪上编辑数据,然后redraw
。
看一下方法定义: https://plot.ly/javascript/plotlyjs-function-reference/#plotly-addtraces
答案 1 :(得分:0)
“清洁”和“更新”是通过不同方式管理的不同事物。
如果您实际上不想删除跟踪,而只是更新,则已经存在一些问题:
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]);