Sorting (sorting) columns in a histogram by column values ​​using dc.js

How can I sort the x-axis (dimension) in the dc.js example by the calculated dimension value instead of the name of the dimension itself?

For example, consider the dc.js example for a line chart:

https://github.com/dc-js/dc.js/blob/master/web/examples/ord.html

How can I sort the x axis in descending order of fruit?

Here is what I tried: ( jsfiddle: http://jsfiddle.net/gautam/re9r9kk7/ )

var counts = [ {name: "apple", cnt: 10}, {name: "orange", cnt: 15}, {name: "banana", cnt: 12}, {name: "grapefruit", cnt: 2}, {name: "grapefruit", cnt: 4} ]; var ndx = crossfilter(counts), fruitDimension = ndx.dimension(function(d) {return d.name;}), sumGroup = fruitDimension.group().reduceSum(function(d) {return d.cnt;}); chart .width(768) .height(380) .x(d3.scale.ordinal()) .xUnits(dc.units.ordinal) .brushOn(false) .xAxisLabel("Fruit") .yAxisLabel("Quantity Sold") .dimension(fruitDimension) .barPadding(0.1) .outerPadding(0.05) .group(sumGroup); 
+6
source share
2 answers

The base mixin has a function called chart.ordering() .

This is especially for changing the order of ordinal values ​​when alphabetically by default is not required. The function you pass to this function takes a pair of {key,value} and returns the value for the order.

To sort the columns in descending order by value, you would do

 chart.ordering(function(d) { return -d.value; }) 
+10
source

This may not be the best way, but basically I did this:

 var sortByCnt = counts.sort(function (a, b) { return a.cnt < b.cnt; }); var names = sortByCnt.map(function (d) { return d.name; }); chart .width(768) .height(380) .x(d3.scale.ordinal().domain(names)) .xUnits(dc.units.ordinal) .brushOn(false) .xAxisLabel("Fruit") .yAxisLabel("Quantity Sold") .dimension(fruitDimension) .barPadding(0.1) .outerPadding(0.05) .group(sumGroup); 

And this gave the result:

enter image description here

+6
source

Source: https://habr.com/ru/post/973544/


All Articles