Reshape data for D3 stacked bar chart

坚强是说给别人听的谎言 提交于 2020-01-07 02:23:15

问题


I have some csv data of the following format, that I have loaded with d3.csv():

Name, Group, Amount
Bill, A, 25
Bill, B, 35
Bill, C, 45
Joe, A, 5
Joe, B, 8

But as I understand from various examples, I need the data like this to use it in a stacked bar chart:

Name, AmountA, AmountB, AmountC
Bill, 25, 35, 45
Joe, 5, 8, NA

How can I transform my data appropriately in the js script? There is also the issue of missing data, as you can see in my example.

Thanks for any help.


回答1:


Yes, you are correct that in order to use d3.stack your data needs re-shaping. You could use d3.nest to group the data by name, then construct an object for each group - but your missing data will cause issues.

Instead, I'd do the following. Parse the data:

var data = `Name,Group,Amount

Bill,A,25
Bill,B,35
Bill,C,45
Joe,A,5
Joe,B,8`;

var parsed = d3.csvParse(data);

Obtain an array of names and an array of groups:

// obtain unique names
var names = d3.nest()
    .key(function(d) { return d.Name; })
    .entries(parsed)
    .map(function(d) { return d.key; });

// obtain unique groups
var groups = d3.nest()
    .key(function(d) { return d.Group; })
    .entries(parsed)
    .map(function(d) { return d.key; });

(Note, this is using d3.nest to create an array of unique values. Other utility libraries such as underscore have a simpler mechanism for achieving this).

Next, iterate over each unique name and add the group value, using zero for the missing data:

var grouped = names.map(function(d) { 
  var item = {
    name:  d
  };
  groups.forEach(function(e) {
    var itemForGroup = parsed.filter(function(f) {
      return f.Group === e && f.Name === d;
    });
    if (itemForGroup.length) {
      item[e] = Number(itemForGroup[0].Amount);
    } else {
      item[e] = 0;
    }
  })
  return item;
})

This gives the data in the correct form for use with d3.stack.

Here's a codepen with the complete example:

https://codepen.io/ColinEberhardt/pen/BQbBoX

It also makes use of d3fc in order to make it easier to render the stacked series.



来源:https://stackoverflow.com/questions/41215704/reshape-data-for-d3-stacked-bar-chart

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