Updating the data of a pack layout from JSON call and redrawing

我的未来我决定 提交于 2019-12-01 04:11:58

I had a hard time understanding how the packs work. Apparently, you just send them a dataset and they return a new dataset that you can use for binding. Much simpler than I'd thought. This solution works and I think most people should be able to move on from here:

var diameter = 960,
    format = d3.format(",d");

var pack = d3.layout.pack()
    .size([diameter - 4, diameter - 4])
    .value(function(d) { return d.size; });

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
  .append("g")
    .attr("transform", "translate(2,2)");

var node;
var currentJson;
var currentUrl = "data1.json";

var getNewData = function() {

    if(currentUrl == "data1.json") {
        currentUrl = "data2.json";
    }
    else {
        currentUrl = "data1.json";
    }

    d3.json(currentUrl, function(error, data) {
        currentJson = data;
        refresh();
    });
}

var refresh = function() {

    node = svg.selectAll(".node")
                    .data(pack.nodes(currentJson));

    node.enter().append("g")
            .classed("node", true)
            .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .append("circle")
            .attr("r", 0)
            .on("click", getNewData)
            .transition()
            .duration(2000)
            .attr("r", function(d) { return d.r; });

    node.transition()
        .duration(2000)
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

    node.select("circle")
        .transition()
        .duration(2000)
        .attr("r", function(d) { return d.r; });
}

d3.select(self.frameElement).style("height", diameter + "px");

getNewData();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!