Koba
Koba

Reputation: 1544

Subset ordinal domain for a bar chart

I have three categories to graph in a bar chart, hence, three bars. However, I would like to graph only two categories, two bars. I have categories A,B,C and I want to graph the subset A,B. Here is a working jsfiddle. The problem is when I put ["A","B"] into the .x(d3.scale.ordinal().domain(["A","B"])) the third bar is still graphed over one of the other ones. Help appreciated.

HTML:

<body> 
    <div id='bar1'><div><h3>Bar 1</h3></div></div>
</body>

JS

var data = [{
    Category: "A",
    ID: "1"
}, {
    Category: "A",
    ID: "1"
}, {
    Category: "A",
    ID: "1"
}, {
    Category: "A",
    ID: "2"
}, {
    Category: "A",
    ID: "2"
}, {
    Category: "B",
    ID: "1"
}, {
    Category: "B",
    ID: "1"
}, {
    Category: "B",
    ID: "1"
}, {
    Category: "B",
    ID: "2"
}, {
    Category: "B",
    ID: "3"
}, {
    Category: "B",
    ID: "3"
}, {
    Category: "B",
    ID: "3"
}, {
    Category: "B",
    ID: "4"
}, {
    Category: "C",
    ID: "1"
}, {
    Category: "C",
    ID: "2"
}, {
    Category: "C",
    ID: "3"
}, {
    Category: "C",
    ID: "4"
}, {
    Category: "C",
    ID: "4"
}, {
    Category: "C",
    ID: "5"
}];

var ndx = crossfilter(data);

var XDimension = ndx.dimension(function (d) {
    return d.Category;
});

dc.barChart("#bar1")
    .width(400).height(150)
    .dimension(XDimension)
    .group(XDimension.group().reduceSum(function(d){return d.ID}))
    .x(d3.scale.ordinal().domain(["A","B"]))
    .xUnits(dc.units.ordinal)

dc.renderAll();

Upvotes: 0

Views: 183

Answers (1)

Gordon
Gordon

Reputation: 20120

There is a request for zooming or focus on ordinal charts here:

https://github.com/dc-js/dc.js/issues/416

However, until that is implemented, I would suggest using the "fake group" technique described here:

https://github.com/dc-js/dc.js/wiki/FAQ#how-do-i-filter-the-data-before-its-charted

A general filtering adapter might look like (untested):

function filtered_group(group, bins) {
  return {
    all:function () {
      return group.all().filter(function(d) {
        return bins.indexOf(d.key) != -1;
      });
    }
  }
};

Then use it like this:

var group0 = XDimension.group().reduceSum(function(d){return d.ID}),
    xgroup = filtered_group(group0, ["A", "B"]);
chart.group(xgroup);

Upvotes: 2

Related Questions