Search code examples
d3.jsdc.jscrossfilter

How to decide dimensions and groups in dc.js?


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.


Solution

  • 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.