Colin
Colin

Reputation: 53

How to sort a dc.js pie chart by its values instead of by its keys

The default sorting is embedded in dc.js:

function pieLayout () {
        return d3.pie().sort(null).value(_chart.cappedValueAccessor);
    }

I would like to override this default and sort by Value instead of Key.

Is there a function I am missing that will do this or is there a way to select the chart using d3 and sort using something like this:

d3.layout.pie().sort(null).value(function(d) { return d.freq; });

Upvotes: 1

Views: 529

Answers (2)

Gordon
Gordon

Reputation: 20150

In dc.js, sorting is handled through BaseMixin.ordering().

The line you have quoted disables D3's sorting because dc.js has already sorted the data. (Looks like pie.sort already defaults to null, so this may be redundant.)

The default for all CapMixin charts (pie and row) is to sort from largest value to smallest. (Clockwise from the top for the pie.)

this.ordering(kv => -kv.value);

source

If you're seeing alphabetic ordering, a likely reason is that your group reduce values are objects, which will coerce to NaN in the above expression. Sorting fails and the group.all() sorting is preserved, which is by key. If this is the case, you may want something like

pieChart.ordering(kv => -kv.value.freq)

Upvotes: 1

Ruben Helsloot
Ruben Helsloot

Reputation: 13139

I'm not too familiar with dc.js, but the returned object from dc.pieLayout is actually a pie chart generator. That means that you can always override the properties of the returned object, by calling .sort() on the return value:

var pieLayout = dc.pieLayout()
    .sort(function(d) { return d.value });

This will override the default set by dc.js

Upvotes: 0

Related Questions