【问题标题】:Adding a path transistion to pie chart向饼图添加路径转换
【发布时间】:2014-04-08 19:04:57
【问题描述】:

我正在用d3.js 绘制饼图。我想在添加新数据时转换饼图。 (我正在使用可重复使用的图表 API)。我首先使用 enter 创建一个图表组,然后将图表弧路径附加到该组:

http://jsfiddle.net/EuK6H/4/

var arcGroup = svg.select(".pie").selectAll(".arc " + selector)
                  .data(pie(data))
                  .enter().append("g")
                  .attr("class", "arc " + selector);
                  if (options.left) {
                      arcGroup.attr('transform', 'translate(' + options.left + ',' + options.top + ')');
                  } else {
                      arcGroup.attr('transform', 'translate(' + options.width / 2 + ',' + options.height / 2 + ')');
                  }

//append an arc path to each group
arcGroup.append("path")
        .attr("d", arc)
        //want to add the transition in here somewhere
        .attr("class", function (d) { return 'slice-' + d.data.type; })
        .style("fill", function (d, i) {
            return color(d.data.amount)
        });
       //...

问题是当新数据进入时,我需要能够转换路径(以及小提琴中显示的文本节点),但输入选择是在父组上进行的。如何添加 transition() 使其适用于路径?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    您可以使用.select(),它将数据传播到选定的元素。然后,您可以根据新数据应用转换。代码看起来像这样:

    var sel = svg.selectAll(".pie").data(pie(newData));
    
    // handle enter + exit selections
    
    // update paths
    sel.select("path")
       .transition()
       .attrTween("d", arcTween);
    

    【讨论】:

    • 谢谢。这似乎不像我预期的那样工作。当我尝试删除路径时出现错误“未捕获的类型错误:对象 [object Array] 没有方法'退出”jsfiddle.net/EuK6H/13我无法删除路径吗?
    • 在使用.data() 显式绑定数据后,进入、更新和退出选择可用,而不是在子选择后。所以你必须做sliceGroups.exit().select(...).remove(),除了在这种情况下,子选择实际上没有意义。如果你不删除整个组,更新时数据匹配会搞砸(匹配空组而不是在你希望添加的地方添加任何内容)。
    • 啊,是的,我明白了。退出子选择并不是我真正需要的。我需要转换子选择
    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多