如何更新D3饼图

时间:2014-03-02 22:07:26

标签: d3.js pie-chart

http://jsfiddle.net/z25SU/

对不起,我知道有很多关于如何做到这一点的材料,我已经通过一些教程看了几个官方要点(比如this one),但我仍然可以不知道这个。

正如您在我的jsfiddle中看到的那样,图表呈现的第一组数据很好 - 但是当我点击更新按钮时,图表根本不会改变。

更新方法 触发,路径“d”值 更新(通过观察Firebug中的元素确认) - 只是路径'新的“d”值与旧的相同。

这里我需要做些什么?我几个小时以来一直在抨击这堵墙,尝试了文档和教程所说的各种不同的事情 - 我只是想不出来。

谢谢!

此外,这是更新方法 - 有人可能会发现问题,甚至不必看小提琴......

function updateData(dataset){
    //console.info(dataset);

    // Set Data
    var allSlices = slicesGroup
            .selectAll(".slice")
                .data(pie(dataset));

    // Create New Slices
    var newSlices = allSlices
            .enter()
            .append("g")
                .attr("class", "slice");

    newSlices
        .append("g")
            .attr("class", "outer")
            .append("path");

    newSlices
        .append("g")
            .attr("class", "inner")
            .append("path");

    // Update All Slices
    allSlices
        .selectAll(".outer")
            .selectAll("path")
                .attr("d", outerArc);

    allSlices
        .selectAll(".inner")
            .selectAll("path")
                .attr("d", innerArc);

    //console.log(newSlices);
    //console.log(allSlices);

    // Remove Old Slices
    allSlices.exit().remove();
};

2 个答案:

答案 0 :(得分:3)

问题与您的嵌套数据结构有关。您的新数据已成功加入“切片”<g>元素,但不会加入您的“内部”和“外部”<g>元素以及<path>元素本身。

修复很简单但不直观。将allSlices.selectAll(".inner").selectAll("path")替换为allSlices.select(".inner").select("path"),将“{”更改为“外部”组。

http://jsfiddle.net/z25SU/1/

使用selection.select() the selected element inherits the updated data from the parent,与.selectAll()相比,任何现有数据都不会更改。教程中并不经常强调这一重要差异。但是,它是有道理的 - 如果你选择了许多带有selectAll的元素,它们每个都应该拥有自己的数据,那么让它们从父级接收到相同的值是没有意义的。

答案 1 :(得分:0)

我更改了输入,更新了代码。这是FIDDLE

您可以在更新功能中使用data2或data3。

// enter selection
var newSlices = allSlices.enter()
    .append("g")
    .attr("class", "slice");

// update selection
allSlices.append("g")
    .attr("class", "outer")
    .append("path")
    .attr("d", outerArc);

// update selection
allSlices.append("g")
    .attr("class", "inner")
    .append("path")
    .attr("d", innerArc);