【问题标题】:How can I create a basic bar chart with unique counts on the y axis and a category on the x axis?如何创建一个基本条形图,在 y 轴上有唯一计数,在 x 轴上有一个类别?
【发布时间】:2014-07-29 19:13:23
【问题描述】:

我想创建一个基本条形图,其中 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();

【问题讨论】:

  • 第二个代码块中有一个流浪的});。是否还有更多正在使用的代码丢失?

标签: javascript d3.js graph dc.js crossfilter


【解决方案1】:

您在这里遇到了一些问题。

首先,您要聚合的数据中有 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())

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多