How to decide dimensions and groups in dc.js?

爱⌒轻易说出口 提交于 2019-12-11 08:48:30

问题


I am new to dc.js and facing issues in deciding dimensions and groups. I have data like this

this.data = [
    {Type:'Type1', Day:1, Count: 20},
    {Type:'Type2', Day:1, Count: 10},
    {Type:'Type1', Day:2, Count: 30},
    {Type:'Type2', Day:2, Count: 10}
]

I have to show a composite chart of two linecharts one for type Type1 and other for Type2. My x-axis will be Day. So one of my dimensions will be Day

var ndx = crossfilter(this.data);
var dayDim = ndx.dimension(function(d) { return d.Day; }) 

How the grouping will be done? If I do it on Count, the total count of a particular Day shows up which I don't want.


回答1:


Your question isn't entirely clear, but it sounds like you want to group by both Type and Day

One way to do it is to use composite keys:

var typeDayDimension = ndx.dimension(function(d) {return [d.Type, d.Day]; }),
    typeDayGroup = typeDayDimension.group().reduceSum(function(d) { return d.Count; });

Then you could use the series chart to generate two line charts inside a composite chart.

var chart = dc.seriesChart("#test");
chart
    .width(768)
    .height(480)
    .chart(function(c) { return dc.lineChart(c); })
    // ...
    .dimension(typeDayDimension)
    .group(typeDayGroup)
    .seriesAccessor(function(d) {return d.key[0];})
    .keyAccessor(function(d) {return +d.key[1];}) // convert to number
    // ...

See the series chart example for more details.




回答2:


Although what Gordon suggested is working perfectly fine, if you want to achieve the same result using composite chart then you can use group.reduce(add, remove, initial) method.

function reduceAdd(p, v) {
  if (v.Type === "Type1") {
    p.docCount += v.Count;
  } 
  return p;
}

function reduceRemove(p, v) {
  if (v.Type === "Type1") {
    p.docCount -= v.Count;
  } 
  return p;
}

function reduceInitial() {
  return { docCount: 0 };
}

Here's an example: http://jsfiddle.net/curtisp/7frw79q6

Quoting Gordon:

Series chart is just a composite chart with the automatic splitting of the data and generation of the child charts.



来源:https://stackoverflow.com/questions/50704742/how-to-decide-dimensions-and-groups-in-dc-js

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