Search code examples
d3.jsdc.jscrossfilter

How to specify x-axis and y-axis input data in dc.js time series graph?


I'm trying to create a time series graph where my x-axis should be a time and y-axis is speed. Im reading both time and speed values from a json array. I can see many examples in the internet where they have defined only x-axis using crossfilter. My json (which is input to the graph) looks like below. Only a sample is shown here.

   [
  {
    "Time": "19-Jan-2018 11:24:49.000 UTC",
    "Speed": 1.885
  },
  {
    "Time": "19-Jan-2018 11:24:59.000 UTC",
    "Speed": 1.875
  },
  {
    "Time": "19-Jan-2018 11:25:00.000 UTC",
    "Speed": 1.878
  },
  {
    "Time": "19-Jan-2018 11:25:01.000 UTC",
    "Speed": 1.876
  }
]

Can someone please suggest how to mark these time in x-axis and speed in y-axis for a time series graph using dc.js


Solution

  • You can do it this way:

    var cf = crossfilter(data);
    
    var timeDimension = cf.dimension(function(d){ return new Date(d.Time); });
    var totalGroup = timeDimension.group().reduceSum(function(d){ return d.Speed; });
    
    var lineChart = dc.lineChart("#line-chart")
        .brushOn(false)
        .width(800)
        .height(200)
        .x(d3.time.scale().domain(d3.extent(data, function(d) {
            return new Date(d.Time);
        })))
        .dimension(timeDimension)
        .group(totalGroup);
    
    dc.renderAll();
    

    Check working demo. (There are strange ticks on x-axis, because of we have very closest dates in dataset that you provide. With full dataset it will look like this).