Sort bars on nvd3 charts

有些话、适合烂在心里 提交于 2020-01-06 15:17:50

问题


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

回答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);
    }


来源:https://stackoverflow.com/questions/26114534/sort-bars-on-nvd3-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!