Configurable Pie Chart Arc Sorting and No-Sorting

2,530 views
Skip to first unread message

Guerino1

unread,
Mar 18, 2012, 10:47:36 AM3/18/12
to d3...@googlegroups.com
Hi,

Sorting a pie chart's Arc's, by value, is pretty straight forward...

        var pie = d3.layout.pie()
            .value(function(d) { return +d.value; })
            .sort(function(a, b) { return b.value - a.value; }); // Sort arcs by size. Loses order of input.
            
So is "not sorting"

        var pie = d3.layout.pie()
            .value(function(d) { return +d.count; })
            .sort(null); // No sortying by arc size.  Maintains order of input.

If I have an input parameter called "sort", where "0 = No Sort" and "1 = Sort", what do you think is the most elegant way to write a function that sorts only on if "sort = 1", to pass into the callback for the ".sort" property?

I'm struggling with the syntax to be able to pass in "sort" along with "a" and "b", simultaneously, as variables that would allow for, both, sort and no-sort situations.

Thanks for any help you can offer.

Frank

Frank Guerino

unread,
Mar 18, 2012, 11:08:09 AM3/18/12
to d3...@googlegroups.com
BTW... this works ".sort(function(a, b) {if (sort==1) { return b.value - a.value; } else { return null; } });" but I think it's too long and I can't seem to get the "if-else" shorthand to work properly.


Thx,

FG

Mike Bostock

unread,
Mar 18, 2012, 11:17:26 AM3/18/12
to d3...@googlegroups.com
You can change the sort function after creating the pie layout. So,
rather than baking the check for sort into the function, changing the
sort function as needed.

function descendingValue(a, b) {
return b.value - a.value;
}

var pie = d3.layout.pie()
.value(function(d) { return +d.value; })
.sort(descendingValue);

Then later:

pie.sort(null); // disable sorting

Or:

pie.sort(descendingValue); // re-enable sorting

After changing the sort function, you'll need to re-run the layout on
the data and update the display.

Mike

Guerino1

unread,
Mar 18, 2012, 11:53:51 AM3/18/12
to d3...@googlegroups.com
Thanks Mike.  I'll try it out.

FG


Reply all
Reply to author
Forward
0 new messages