d3.js - 具有进入-更新-退出逻辑的 d3 折线图

标签 d3.js

今天我用输入-更新-退出逻辑创建了一个简单的条形图——一切正常。现在我将对折线图做同样的事情——图表的整个数据集可以随时更改,所以我会顺利更新图表。我找不到折线图和输入-更新-退出逻辑的好例子(或者我看错了)。目前我必须记住,如果第一次调用图表或要更新的数据(数据已更改) - 这是我的脏版本:

   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/

相关文章:

javascript - d3 和弦 : center text on circle

javascript - 如何显示 d3.js 美国 map ,其中包含指向它的州之外的某个州名称

javascript - d3.js 示例在 Github Pages 上托管时不起作用?

javascript - 参数 'd3Ctrl' 不是函数,未定义

javascript - d3js v4 : Add nodes to force-directed graph

javascript - Chrome svg 渲染问题 - d3 - 折线

javascript - 使用带有合并的通用更新模式输入元素时的 D3 V4 转换

javascript - NVD3 - 将 JSON url 数据与 LinePlusBarChart 结合使用(映射值)

javascript - d3 不透明度转换 flash 最终状态

javascript - D3 V4 - 使用合并与一般更新模式