2013-01-11 239 views
7

我试图想象团队协作的数据,在这样的方式创建的对象的层次结构:拼合与d3.js嵌套

Chart that displays the share of the different collaboration artifact types for each team and week

不同颜色的图表中有不同的协作工件类型。

从源中的数据是这样的:

var json = [ 
    { 
     "teamLabel": "Team 1", 
     "created_date": "2013-01-09", 
     "typeLabel": "Email" 
     "count": "5" 
    }, 
    { 
     "teamLabel": "Team 1", 
     "created_date": "2013-01-10", 
     "typeLabel": "Email" 
     "count": "7" 
    }, 
    /* and of course, a lot more data of this kind */ 
] 

注意,数据是单天定。因此,对于上面的可视化,我需要根据一年中的第一周来汇总数据。团队名称和工件类型需要保留,并用作分组属性。代码如下:

// "2013-01-09" 
var dateFormat = d3.time.format.utc("%Y-%m-%d"); 

// "2013-02" for the 2nd week of the year 
var yearWeek = d3.time.format.utc("%Y-%W"); 

var data = d3.nest().key(function(d) { 
     return d.teamLabel; 
    }).key(function(d) { 
     var created_date = dateFormat.parse(d.created_date); 
     return yearWeek(created_date); 
    }) 
    .key(function(d) { 
     return d.typeLabel; 
    }).rollup(function(leaves) { 
     return d3.sum(leaves, function(d) { 
       return parseInt(d.count); // parse the integer 
      }); 
     } 
    ) 
    .map(json); 

这会导致基于嵌套键的对象层次结构。我不知道如何从这个上面的图表,所以我宁愿寻找一种方式来data转换成以下结构:

[ 
    // This list contains an element for each donut 
    { 
     "teamLabel": "Team 1", 
     "createdWeek": "2013-02", 
     "values": [ 
      // This list contains one element for each type we found 
      { 
       "typeLabel": "Email", 
       "count": 12 
      }, 
      { 
      ... 
      } 
     ] 
    }, 
    { 
    ... 
    } 
] 

这样一来,我可以使用createdWeekteamLabel为x上的定位 - 和y轴,并且values下的信息可以传递到d3.layout.pie()

有没有一种干净的方式来做这种数据转换?如果您需要任何澄清或进一步的细节,请让我知道。

+1

你有没有找到如何去做这个? –

+0

@cyroxx我不知道我理解你的问题;你想将你提交的'json'数据转换为按队列分组的新阵列格式? – hitautodestruct

+0

我很困惑你为什么称之为扁平化,看起来你正在为最初的扁平数据添加图层。 (我正在寻找拼合嵌套数据集。) – punstress

回答

3

这是你怎么做:

var flat = data.entries().map(function(d){ 
    return d.value.entries().map(function(e){ 
     return { 
      "teamLabel": d.key, 
      "createdWeek": e.key, 
      "values": e.value.entries().map(function(f){ 
       return {"typeLabel": f.key, "count": f.value} 
      }) 
     } 
    }) 
}).reduce(function(d1,d2){ return d1.concat(d2) },[]); 

请注意,我在为了使用map.entries()辅助函数使用标准的JavaScript对象的d3.map代替。我想这就是你试图通过的事实,你正在使用判断什么:

.map(json); // whereas I used .map(json, d3.map) 

,而不是

.entries(json); 

的jsfiddle链接在这里:

http://jsfiddle.net/RFontana/KhX2n/

+1

你的链接不显示正确的json? – thatOneGuy