今天我用输入-更新-退出逻辑创建了一个简单的条形图——一切正常。现在我将对折线图做同样的事情——图表的整个数据集可以随时更改,所以我会顺利更新图表。我找不到折线图和输入-更新-退出逻辑的好例子(或者我看错了)。目前我必须记住,如果第一次调用图表或要更新的数据(数据已更改) - 这是我的脏版本:
var channelGroup = d3.select(".ch1");
// init. Line Chart
if (firstLoad) {
channelGroup
.append('path')
.attr("class", "line")
.style("stroke", channel.Color)
.transition()
.ease("linear")
.duration(animChart / 2)
.attr('d', line(channel.DataRows));
}
// update Line Chart
else {
channelGroup
.selectAll("path")
.data([channel.DataRows])
.transition()
.ease("linear")
.duration(animChart / 2)
.attr("d", function (d) { return line(d); });
}
我怎样才能以一种好的方式实现这一点?...谢谢!
最佳答案
您混合了两种不同的方法,一种将数据绑定(bind)到线路,另一种只是将数据传递给线路函数。任何一个都可以工作(只要你只有一行),但如果你想摆脱你的 if/else 构造,你仍然需要将处理输入/附加元素的语句与更新语句分开它。
选项 1 (不绑定(bind)数据,只调用函数):
var linegraph = channelGroup.select('path');
if ( linegraph.empty() ) {
//handle the entering data
linegraph = channelGroup.append('path')
.attr("class", "line")
.style("stroke", channel.Color);
}
linegraph
.transition()
.ease("linear")
.duration(animChart / 2)
.attr('d', line(channel.DataRows));
选项 2 (使用数据连接):
var linegraph = channelGroup.selectAll("path")
.data([channel.DataRows]);
linegraph.enter().append('path')
.attr("class", "line");
linegraph
.transition()
.ease("linear")
.duration(animChart / 2)
.attr("d", line); //This is slightly more efficient than
//function (d) { return line(d); }
//and does the exact same thing.
//d3 sees that `line` is a function, and
//therefore calls it with the data as the
//first parameter.
关于d3.js - 具有进入-更新-退出逻辑的 d3 折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22508133/