dc.js渲染条形图

use*_*781 3 javascript d3.js crossfilter dc.js

我正在尝试使用dc.js库渲染条形图.我的csv数据集的格式如下:

q,年,类别,子类别,总数,
q1,2010,x,xa,200
q2,2010,y,yb,100
q3,2010,x,xa,300
q4,2010,z,zb,45
q1,2010, x,xa,80
q2,2010,y,yb,200
q3,2010,x,xc,301
q4,2010,z,za,205
q1,2011,x,xa,80
q2,2011,y,yb,200
q3,2011,x,xc,301
q4,2011,z,za,205

到目前为止,我能够获得一个条形图,但实际数据没有呈现给图表,x轴上的缩放也是关闭的,因为它应该是根据年份.我很难将数据附加到图表中.这就是我能得到的一切

在此输入图像描述

我通过d3.csv加载数据如下:

d3.csv("records.csv", function(csv) {
    var data = crossfilter(csv);

    var fiscalyear = data.dimension(function (d) {
        return d.year;
    });

    var spendGroup = fiscalyear.group().reduce(
        function(p,v) {
            return p.total += v.total;
        },
        function(p,v) {
            return p.total -= v.total;
        },
        function() {
            return  {totalSpend:0};
        }
    );

fiscalyearchart.width(600)
    .height(300)
    .margins({top: 10, right: 50, bottom: 30, left: 60})
    .dimension(fiscalyear)
    .group(spendGroup)
    .x(d3.scale.linear().domain([2010,2013]))
    .renderHorizontalGridLines(true)
    .centerBar(true)
    .elasticY(true)
    .brushOn(true);

    dc.renderAll();

});
Run Code Online (Sandbox Code Playgroud)

JRi*_*out 8

默认值valueAccessor确定Y轴上每列的高度.默认情况下,它假定您可以使用crossfilter组返回的值.所以它期望类似于:

console.log(group.all())

// [{key: 2010, value: 1},
//  {key: 2011, value: 2}]
Run Code Online (Sandbox Code Playgroud)

但相反,您正在使用返回对象的自定义reduce函数.

您的对象将如下所示:

console.log(group.all())

// [{key: 2010, value: {total:NaN, totalSpend:0}},
//  {key: 2011, value: {total:NaN, totalSpend:0}}]
Run Code Online (Sandbox Code Playgroud)

DC不知道如何使用以下值:{total:NaN, totalSpend:0}.您需要传递valueAccessor来提取数字值

chart.valueAccessor(function(d) {return d.totalSpend;});
Run Code Online (Sandbox Code Playgroud)

此外,我认为你有一个错字,真的想用p.totalSpend而不是p.total.但是你可以通过以下方式进一步简化:

var spendGroup = fiscalyear.group().reduce(
    function(p,v) {
        return p += v.total;
    },
    function(p,v) {
        return p -= v.total;
    },
    function() {
        return 0;
    }
);
Run Code Online (Sandbox Code Playgroud)

这将返回一个.valueAccessor功能,直流可以理解,无需定制.更简单的是,crossfilter已经为此提供了便利功能:

var spendGroup = fiscalyear.group().reduceSum(function(d) {return d.total;});
Run Code Online (Sandbox Code Playgroud)

DC具有创建回调的实用程序:

var spendGroup = fiscalyear.group().reduceSum(dc.pluck('total'));
Run Code Online (Sandbox Code Playgroud)