作者:堕落戥囝_631 | 来源:互联网 | 2023-05-25 19:02
我写了一个可重复使用的d3折线图(下面的代码).不幸的是,它只在更新传递给它的数据数组时才能正确更新; 如果传递一个新的数据数组,它根本不会更新 - 你可以在这个jsfiddle中看到它.
这是html,主要是嵌入式演示调用脚本:
您可以看到它第二次调用chart
它直接更新数据数组中的单个点(pts[0][3][1] = 0.5
),并且图表可以正常设置动画.第三次传递新数据数组时,图表不会更改.
这是demoChart.js
代码(基于可重用的图表模式):
function demoChart() {
function xs(d) { return xScale(d[0]) }
function ys(d) { return yScale(d[1]) }
var xScale = d3.scale.linear().domain([0, 500]).range([0, 400]),
yScale = d3.scale.linear().domain([0, 1]).range([400, 0]),
line = d3.svg.line().x(xs).y(ys);
function chart(selection) {
selection.each(function(data) {
console.log("passed data: ", data);
// Select the svg element, if it exists; otherwise create it
var svg = d3.select(this).selectAll("svg").data([1]);
var svgGEnter = svg.enter().append("svg").append("g");
// Select/create/remove plots for each y, with the data
var plots = svg.select("g").selectAll(".plot").data(data);
plots.exit().remove();
var plotsEnter = plots.enter().append("g").attr("class","plot");
plotsEnter.append("path");
// Update the line paths
plots.selectAll("path")
.transition()
.attr("d", function(d,i) {
console.log("transitioning line with data: ", d);
return line.apply(this, arguments);
});
svg.attr("width", 400).attr("height", 400);
});
}
return chart;
}
我怀疑我遗漏了一些关于d3如何工作的基本信息.
如何在传递新数据阵列时正确更新图表?
1> meetamit..:
在哪里更新线路路径,通过
plots.selectAll("path")
它需要
plots.select("path")
看看mbostock对微妙但至关重要的区别的解释.
这是一个工作小提琴,它还添加了第二条路径,以验证它是否适用于绘图.