我想创建一个基本的条形图,其中 x 轴为“类型”,y 轴为唯一计数。我似乎找不到 x 轴上有类型的示例(甚至在教程中也找不到)
我有以下代码:
<div id='dc-bar-chart'></div>
这是数据
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"
}];
这是我的代码
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();
最佳答案
您在这里遇到了一些问题。
首先,您聚合的数据中有 NaN,因此您需要将 YDimension 更改为类似的内容
var YDimension = XDimension.group().reduceSum(function (d) {return isNaN(d.total) ? 0 : d.total;});
让 Crossfilter 正确求和。
然而,实际的答案与你的 x 尺度有关。您目前只是不包括一个,但听起来您所说的是 Ordinal Scale 。序数刻度是您通常想到的条形图刻度;它们是一种具有离散域的尺度。在这种情况下,您可以尝试添加序数比例,如下所示:
.x(d3.scale.ordinal().domain(["visa", "cash", "tab"]))
所以它使用序数尺度来代替。由于您使用的是 dc.js,因此您还需要指定
.xUnits(dc.units.ordinal)
以便它知道使用序数标记。
总的来说,我用过
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);
对我来说效果很好。根据您的 dc.js 版本,您也许可以省略域并让 dc.js 自动计算出来。在这种情况下,您可以使用
.x(d3.scale.ordinal())
关于javascript - 如何创建在 y 轴上具有唯一计数、在 x 轴上具有类别的基本条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023221/