Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.layout.pack stacks circles when sort is ascending

I have a dataset such that when sorted in ascending order the circles end up 'stacked' but appear properly distributed when using null or descending sort order.

ascending

descending

null

Complete example is here: http://jsfiddle.net/SXLHx/3/.

Anyone have a suggestion?



    sortItems = function(a,b) {
        var str,result;
        switch(sortOrder%3){
            case 0:
                str = 'ascending';
                result = a.size - b.size;
                break;
            case 1:
                str = 'descending';
                result = b.size - a.size;
                break;
            default:
                str = 'null';
                result = null;
        }
        document.getElementById("sortLbl").innerHTML = str;
        return result;
    };

    pack = d3.layout.pack().sort(sortItems);

Some additional info:

I found that if I remove at least two of the blocks entries that have the value 0 (didn't matter which two but it had to be two) the layout is fine. http://jsfiddle.net/SXLHx/4/

Also, applying a filter to not append circles with 0 value like so:



    // Create circles
    node.append("circle")
        .filter(function(d){return d.size > 0;})
        .attr("r",function(d){return d.r;});

does not correct the layout issue. Maybe I'm filtering incorrectly?

like image 976
user1052313 Avatar asked Sep 30 '22 19:09

user1052313


1 Answers

You just have a couple of mistakes in the portion of code that is supposed to set new order and update the layout. It should look like this: (it is even simpler than what is currently in the code)

pack
  .sort(sortItems)
  .nodes({blocks:data});

node
  .attr("transform",function(d){
      return "translate("+d.x+","+d.y+")";
  })
  .selectAll("circle")
  .attr("r",function(d){return d.r;});

I solved zero values with this line in pack initialization:

.value(function(d){return Math.max(0.01, d.size);});

Here is jsfiddle.

Here is video of execution:

enter image description here

(note that after third button-press, circles do not return to original order, but this is due to other reasons that don't have direct connection to original problem (which is about ascending/descending order in circle pack)).

Hope this helps.

like image 155
VividD Avatar answered Oct 06 '22 01:10

VividD