0

Is there a easy way to sort bars (ascending or descending) on Nvd3 discreteBarChart or on the HorizontalBarChart. I think a function should be added to the main lib (Nvd3) so that the option can be used as below:

.sortAscending(true) //Used for ascending bars according to their value
  or
.sortDescending(true)  //Used for descending bars according to their value
user3172663
  • 312
  • 3
  • 14

1 Answers1

1

try this, i implemented in my application, include this in your addGraph method before returning chart object

var parent = $('svg').parent().attr("id");

//add a button to your DIV and give onclick evet function

d3.select("#"+parent).append('a').attr('href',"javascript:void(0)")
 .text('Sort').on("click", sortBars).html('Sort');

//sorting function

var sortOrder;
var sortBars = function(){

    if( !sortOrder || sortOrder == null)
        sortOrder = true;
    else sortOrder = false;
        var historicalBarChart11 ;
    var data1 = JSON.parse(JSON.stringify(data));//cloning object
    sortdata = data1[0].values;
        sortdata.sort(function(a,b){
        if(sortOrder)
            return a["value"]-b["value"];//[1];
        else
            return b.value-a.value;//[1];
        });
        for(var i=0;i<sortdata.length;i++){
            data1[0]["values"][i] = sortdata[i];
        }
        d3.select('svg').datum(data1).transition().duration(500).call(chart);
    }
gani
  • 99
  • 1
  • 10
  • NOTE there is a small bug: in the sorting: if (sortOrder) return a["value"] - b["value"];//[1]; else return b["value"] - a["value"];//[1]; – shelbypereira May 29 '15 at 13:10