重塑D3堆叠条形图的数据 [英] Reshape data for D3 stacked bar chart

查看:99
本文介绍了重塑D3堆叠条形图的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用以下格式加载的csv数据,已经用d3.csv()加载了:

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

如何在js脚本中适当地转换数据?如您在我的示例中所见,还有数据丢失的问题.

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.

感谢您的帮助.

推荐答案

是的,为了使用d3.stack,您的数据需要重新整形是正确的.您可以使用d3.nest按名称对数据进行分组,然后为每个组构造一个对象-但是丢失的数据将导致问题.

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 =`名称,组,金额

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

(请注意,这是使用d3.nest创建唯一值数组.其他实用程序库(例如下划线)具有更简单的实现此目的的机制).

(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;
})

这将以正确的格式提供数据,以用于d3.stack.

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

这是一个带有完整示例的codepen:

Here's a codepen with the complete example:

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

它还使用 d3fc ,以便更轻松地渲染堆叠的系列.

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

这篇关于重塑D3堆叠条形图的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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