Rac*_*ole 2 javascript charts d3.js
我写了一个可重复使用的d3折线图(下面的代码).不幸的是,它只在更新传递给它的数据数组时才能正确更新; 如果传递一个新的数据数组,它根本不会更新 - 你可以在这个jsfiddle中看到它.
这是html,主要是嵌入式演示调用脚本:
<style>
path { stroke: purple; stroke-width: 2px; fill: none; }
</style>
<body>
<div id="demo"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="demoChart.js"></script>
<script>
var chart = demoChart();
var pts = [[[0,0],[200,0.25],[500,1]]];
d3.select("#demo").datum(pts).call(chart);
setTimeout(function() {
console.log("Modifying data array");
pts[0][2][1] = 0.5;
d3.select("#demo").datum(pts).call(chart);
},1000);
setTimeout(function() {
console.log("Passing new data array");
d3.select("#demo").datum([[[0,1],[200,0.45],[500,0]]]).call(chart);
},2000);
</script>
Run Code Online (Sandbox Code Playgroud)
您可以看到它第二次调用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;
}
Run Code Online (Sandbox Code Playgroud)
我怀疑我遗漏了一些关于d3如何工作的基本信息.
如何在传递新数据阵列时正确更新图表?
在哪里更新线路路径,通过
plots.selectAll("path")
Run Code Online (Sandbox Code Playgroud)
它需要
plots.select("path")
Run Code Online (Sandbox Code Playgroud)
这是一个工作小提琴,它还添加了第二条路径,以验证它是否适用于绘图.