对d3.js堆叠条形图进行排序 [英] Sorting a d3.js stacked bar chart

查看:366
本文介绍了对d3.js堆叠条形图进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,此堆叠条形图根据每个条的总数从左到右排序。我还如何排序每个单独的酒吧,这样,而不是排序每个单独的酒吧由键(即5岁以下是65岁以上是在顶部),它将排序每个单独的酒吧值(最大



目前,CA栏目是堆叠的(从下到上)

  CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496 

我希望它堆叠如下(从下到上)

  CA,10604510,8819342,4499890,4114496,3853788,2704659,2159981 

为了清楚起见,我需要能够在客户端执行此操作(即更改原始数据的顺序或格式不是一个选项)。

解决方案

您链接的条形图示例直接从CSV(通过颜色标尺的域)获取值的顺序。实际堆叠是在这行:

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

堆叠顺序取决于 color.domain返回的名称顺序()。要更改顺序,您需要做的是对您到达的值进行排序。要根据单个细分的值对每个条进行排序,您可以使用

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

这会从颜色范围的域中获取名称,然后按照值的降序对它们排序,它们在 sort 函数中引用。这个新数组 order 然后用于堆叠:

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

其余代码保持不变。完成演示此处


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 individual bar by the key (i.e. Under 5 years old is at the bottom and 65 years and over is at the top) it would sort each individual bar by the value (largest at the bottom and smallest at the top).

For example:

Currently the CA bar is stacked like this (from bottom to top)

CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496

I would like it stacked like this (from bottom to top)

CA,10604510,8819342,4499890,4114496,3853788,2704659,2159981

Just to be clear, I need to be able to do this on the client side (i.e. changing the order or format of the original data is not an option).

解决方案

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.

这篇关于对d3.js堆叠条形图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆