dadadima
dadadima

Reputation: 938

Using a year-field on the x-axis of a lineChart in dc.js

I am having troubles to implement a data parser using d3. I have a field in my csvdataset that looks like this:

.., year, ..

.., 1987, ..
.., 1988, ..
.., 1989, ..
.., 1990, ..

I would like to use this year dimension on a x-axis of a dc.lineChart. The following is my implementation using crossfilter.js

var ndx = crossfilter(data);    
var yearDim  = ndx.dimension(function(d) {return d.year});

At the moment I am using the following solution, which as you can see does not achieve the wanted result:

data.forEach(function(d) {
   d.year = parseInt(d.year);
});
...
...
yearChart
   .width(870)
   .height(500)
   .dimension(yearDim)
   .group(numberPerYear)
   .x(d3.scaleLinear().domain([1987,2015]))
   .elasticY(true)
   .controlsUseVisibility(true)
   .yAxis().ticks(5);

However, this results in having integer on the x-axis. I tried also to create a parser for the date, but I do not know how to pass the parameter after and also I am not sure whether this is the right solution, since the function I found online are deprecated (v.3).

  var dateFormatSpecifier = '/%Y';
  var dateFormat = d3.timeFormat(dateFormatSpecifier);
  var dateFormatParser = d3.timeParse(dateFormatSpecifier);

Upvotes: 1

Views: 57

Answers (1)

Terry
Terry

Reputation: 66103

You should be using d3.scaleTime() instead of d3.scaleLinear(). You can simply set the domain to exactly 00:00 for the start and end dates for the domain:

.x(d3.scaleTime().domain([
    new Date("January 1, 1987 00:00:00"),
    new Date("January 1, 2015 00:00:00")
]));

Remember to transform the d.year into a Date object:

var yearDim  = ndx.dimension(function(d) { return new Date(d.year); });

Upvotes: 3

Related Questions