DC.js barChart不显示日期轴

时间:2017-05-15 07:32:06

标签: dc.js

我正在尝试显示一个显示日期计数的条形图,但条形图不会绘制,我在控制台中收到NaN错误。

有人可以告诉我哪里出错了吗?

var data1=[{budget:1,billed:1,fees:1,feeVariance:0,Documents:"URL",date:"01 February 2017"},
{budget:7,billed:6,fees:1,feeVariance:3,Documents:"URL",date:"01 February 2018"},
{budget:10,billed:1,fees:4,feeVariance:3,Documents:"URL",date:"01 May 2017"},
{budget:14,billed:2,fees:4,feeVariance:2,Documents:"URL",date:"15 May 2017"},
{budget:2,billed:1,fees:1,feeVariance:0,Documents:"URL",date:"02 June 2016"}];

var facts = crossfilter(data1);
var dateDimension = facts.dimension(function(d) { return new Date(d.date); });
var dateGroup = dateDimension.group().reduceCount(function(d){return new Date(d.date);});

var minDate = dateDimension.bottom(1)[0].date;
var maxDate = dateDimension.top(1)[0].date;

dc.barChart("#chart1")
  .width(800)
  .dimension(dateDimension)
  .group(dateGroup)
  .brushOn(false)
  .x(d3.time.scale().domain([minDate,maxDate]))
  .xUnits(d3.time.months);

dc.renderAll();

1 个答案:

答案 0 :(得分:0)

您需要首先确定日期格式,以便dc.js可以将其理解为日期而不仅仅是字符串。

首先,创建一个变量来设置日期格式:

var dateFormat = d3.time.format('%d %B %Y');

然后是一个制作日期和月份字段的函数:

data1.forEach(function(d) {
    d.date = dateFormat.parse(d.date);
    d.month = d3.time.month(d.date);
});

然后更改维度和组以使用d.month

var dateDimension = facts.dimension(function(d) { return d.month; });
var dateGroup = dateDimension.group().reduceCount(function(d){return 
d.month;});

这将按月分组,并按月提供计数/总数。

这是完整的代码:

var dateFormat = d3.time.format('%d %B %Y');

var data1=[{budget:1,billed:1,fees:1,feeVariance:0,Documents:"URL",date:"01 
February 2017"},
{budget:7,billed:6,fees:1,feeVariance:3,Documents:"URL",date:"01 February 2018"},
{budget:10,billed:1,fees:4,feeVariance:3,Documents:"URL",date:"01 May 2017"},
{budget:14,billed:2,fees:4,feeVariance:2,Documents:"URL",date:"15 May 2017"},
{budget:2,billed:1,fees:1,feeVariance:0,Documents:"URL",date:"02 June 2016"}];

var facts = crossfilter(data1);

data1.forEach(function(d) {
d.date = dateFormat.parse(d.date);
d.month = d3.time.month(d.date);
});

var dateDimension = facts.dimension(function(d) { return d.month; });
var dateGroup = dateDimension.group().reduceCount(function(d){return d.month;});

var minDate = dateDimension.bottom(1)[0].date;
var maxDate = dateDimension.top(1)[0].date;

dc.barChart("#chart1")
.width(800)
.dimension(dateDimension)
.group(dateGroup)
.brushOn(false)
.x(d3.time.scale().domain([minDate,maxDate]))
.xUnits(d3.time.months);

dc.renderAll();

我在图表中添加了一些额外的属性,以确保所有条形图都正确显示:

.gap(2)
.outerPadding(5)
.centerBar(true)
.elasticX(true)
.xAxisPadding(20)

jsfiddle示例: jsfiddle