How can I create a basic bar chart with unique counts on the y axis and a category on the x axis?
-
21-12-2019 - |
Question
I'd like to create a basic bar chart with 'type' on the x-axis and unique count on the y-axis. I can't seem to find an example with type on the x axis (not even in the tutorial)
I have the following code:
<div id='dc-bar-chart'></div>
This is the Data
var data = [{
date: "2011-11-14T16:17:54Z",
quantity: 2,
total: 190,
tip: 100,
type: "tab"
}, {
date: "2011-11-14T16:20:19Z",
quantity: 2,
total: NaN,
tip: 100,
type: "tab"
}, {
date: "2011-11-14T16:28:54Z",
quantity: 1,
total: 300,
tip: 200,
type: "visa"
}, {
date: "2011-11-14T16:30:43Z",
quantity: 2,
total: 90,
tip: 0,
type: "tab"
}, {
date: "2011-11-14T16:48:46Z",
quantity: 2,
total: 90,
tip: 0,
type: "tab"
}, {
date: "2011-11-14T16:53:41Z",
quantity: 2,
total: 90,
tip: 0,
type: "tab"
}, {
date: "2011-11-14T16:54:06Z",
quantity: 1,
total: NaN,
tip: null,
type: "cash"
}, {
date: "2011-11-14T17:02:03Z",
quantity: 2,
total: 90,
tip: 0,
type: "tab"
}, {
date: "2011-11-14T17:07:21Z",
quantity: 2,
total: 90,
tip: 0,
type: "tab"
}, {
date: "2011-11-14T17:22:59Z",
quantity: 2,
total: 90,
tip: 0,
type: "tab"
}, {
date: "2011-11-14T17:25:45Z",
quantity: 2,
total: 200,
tip: null,
type: "cash"
}, {
date: "2011-11-14T17:29:52Z",
quantity: 1,
total: 200,
tip: 100,
type: "visa"
}];
Here is the code I have
ndx = new crossfilter(data)
var XDimension = ndx.dimension(function (d) {return d.type;});
var YDimension = XDimension.group().reduceSum(function (d) {return d.total;});
dc.barChart("#dc-bar-chart")
.width(480).height(150)
.dimension(XDimension)
.group(YDimension)
.centerBar(true)
.gap(56)
});
dc.renderAll();
Solution
You've got a few issues in here.
First, you've got NaNs in the data you're aggregating, so you'll need to change your YDimension to something like
var YDimension = XDimension.group().reduceSum(function (d) {return isNaN(d.total) ? 0 : d.total;});
to get Crossfilter to sum it properly.
The actual answer, though, is about your x scale. You're currently just not including one, but it sounds like what you're talking about is an Ordinal Scale. Ordinal scales are the scales you typically think of for bar charts; they're a type of scale that has a discrete domain. In this case, you could try adding an ordinal scale like so:
.x(d3.scale.ordinal().domain(["visa", "cash", "tab"]))
so it uses an ordinal scale instead. Since you're using dc.js, you'll also need to specify
.xUnits(dc.units.ordinal)
so that it knows to use ordinal marks.
Overall, I used
dc.barChart("#dc-bar-chart")
.width(480).height(150)
.x(d3.scale.ordinal().domain(["visa", "cash", "tab"]))
.xUnits(dc.units.ordinal)
.dimension(XDimension)
.group(YDimension)
.centerBar(false);
and it worked fine on my end. Depending on your dc.js version, you may be able to omit the domain and let dc.js figure it out automatically. In that case, you could just use
.x(d3.scale.ordinal())