Circle-packing diagram - transition between two set of values

后端 未结 1 1434
北海茫月
北海茫月 2021-01-14 18:33

I have a diagram very similar to circle packing

At some point, a user wants to see some different data. Obviously, a different diagram can be displayed immediately,

1条回答
  •  有刺的猬
    2021-01-14 19:13

    It looks that I finally resolved all issues. jsfiddle is here.

    Here is the whole code (except data definition and button creation) that handles smooth circle pack layout transition:

    var diameter = 500,
        format = d3.format(",d"),
        dataSource = 2;
    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);
    
    var data = getData();
    
    var vis = svg.datum(data).selectAll(".node")
        .data(pack.nodes)
       .enter()
        .append("g");
    
    var titles = vis.append("title")
        .attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; })
        .text(function(d) { return d.name +
            (d.children ? "" : ": " + format(d.value)); });
    
    var circles = vis.append("circle")
        .attr("stroke", "black")
        .style("fill", function(d) { return !d.children ? "tan" : "beige"; })
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", function(d) { return d.r; });
    
    updateVis();
    
    function updateVis() {
    
        if (dataSource == 0)
            pack.value(function(d) { return d.size; });
        if (dataSource == 1)
            pack.value(function(d) { return 100; });
        if (dataSource == 2)
            pack.value(function(d) { return 1 +
                     Math.floor(Math.random()*301); });
    
        var data1 = pack.nodes(data);
    
        titles.attr("x", function(d) { return d.x; })
            .attr("y", function(d) { return d.y; })
            .text(function(d) { return d.name +
                (d.children ? "" : ": " + format(d.value)); });
    
        circles.transition()
            .duration(5000)
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; })
            .attr("r", function(d) { return d.r; });
    };
    

    0 讨论(0)
提交回复
热议问题