Sorting a d3.js stacked bar chart

前端 未结 1 1327
既然无缘
既然无缘 2021-01-06 15:00

Currently this stacked bar chart is sorted from left to right based on the total of each bar. How would I also sort each individual bar so that instead of sorting each indiv

相关标签:
1条回答
  • 2021-01-06 15:30

    The bar chart example you've linked to gets the order of the values directly from the CSV (through the domain of the colour scale). The actual stacking is done in this line:

    d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
    

    The stacking order depends on the order the names are returned by color.domain(). To change the order, all you need to do is sort the values you're getting there. To sort them, for each bar individually, by the values of the individual segments, you can use

    var order = color.domain().map(function(d) { return d; })
                     .sort(function(a, b) { return +d[b] - +d[a]; });
    

    This gets the names from the domain of the colour scale and then sorts them in descending order by the values, which are referenced in the sort function. This new array order is then used for the stacking:

    d.ages = order.map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
    

    The rest of the code remains unchanged. Complete demo here.

    0 讨论(0)
提交回复
热议问题