0

I've have the following dataset.

[{..... att1: a, hits: 2},
{..... att1: a, hits: 2},
{..... att1: a, hits: 3},
{..... att1: b, hits: 2},
{..... att1: b, hits: 2},
{..... att1: c, hits: 9},
]

I want to create a bar chart where x values would be ranges '0-5', '5-10', '10+' and y values would be number of keys that fall in that range. ie. ('0-5', 1), ('5-10', 2), ('10+', 0)

bashhike
  • 129
  • 1
  • 10

1 Answers1

2

Create a dimension that transforms your data into a set of ordinal values that match your buckets. Then group on that dimension. Your group will count the number of records that fall into each bucket.

var data = [{att1: 'a', hits: 2},
  {att1: 'a', hits: 2},
  {att1: 'a', hits: 3},
  {att1: 'b', hits: 2},
  {att1: 'b', hits: 2},
  {att1: 'c', hits: 9},
];
var cf = crossfilter(data);
var dim = cf.dimension(function(d) {
  if(d.hits <= 5) return '0-5';
  if(d.hits <= 10) return '5-10';
  return '10+'; 
});
var grp = dim.group();
console.log(grp.all());

Working example (check the console): https://jsfiddle.net/esjewett/u10h4xsu/2/

Then you can build your dc.js bar chart based on this.

var barChart = dc.barChart("#bar");

barChart.dimension(dim)
    .group(grp)
  .x(d3.scale.ordinal().domain(['0-5','5-10','10+']))
  .xUnits(dc.units.ordinal);

dc.renderAll();

Example with the bar chart: https://jsfiddle.net/esjewett/u10h4xsu/4/

Ethan Jewett
  • 6,002
  • 16
  • 25
  • this what I've done. But if you see the results are wrong. I want to group by total hits instead of hits as in if you see the data set total hits for `a=5, b=4, c=9` so I the expected Y scale values are `(0-5, 1), (5-10, 2), (10+, 0)`. – bashhike Aug 31 '16 at 05:13
  • 1
    That's going to be a problem. You can certainly do something like this using fake groups, but what would it mean to filter on this chart? If you just want to display and not filter, then create a fake group: https://github.com/dc-js/dc.js/wiki/FAQ#combine-groups – Ethan Jewett Aug 31 '16 at 15:40