Grouping data by date


I’m trying to break up an array of data which is a series of dates and power into sub-arrays containing date and power. I understand underscore.js (_groupBy) helps in this regard but I’m not sure how to use it. Any other way to do it is also fine.

Any help would be appreciated. Notebook -

Gani -

Can you explain a little more about what you are trying to accomplish? For example, do you want to group your data by day of the week and then plot the sum? Or something else?

Hi Mike, that’s exactly what I’m trying to do. Trying to get energy by date. So area under curve to get W*hr. If I know the basics of getting the data bunched together (date, value) I can extend to week also.

Thx, Gani-

Sure, here are two ways you can do that.

Vega-Lite supports aggregation, so you can change a spec like this

  encoding: {
    x: {field: 'date', type: 'temporal'},
    y: {field: 'value', type: 'quantitative'}

to something like this

  encoding: {
    x: {field: 'date', type: 'temporal', timeUnit: 'yearmonthdate'},
    y: {field: 'value', type: 'quantitative', aggregate: 'sum'}

and it’ll group and sum your data by date. See the Time Unit and Aggregation documentation.

You can do something similar at the data level in D3 using d3.rollup:

sumByDate = d3.rollup(
  data => d3.sum(data, d => d.value),
  d => +d3.timeDay(

In this case, data is an array of {date, value} objects. So the key function d => +d3.timeDay( computes the date (midnight in local time) to group objects, and then the rollup function data => d3.sum(data, d => d.value) computes the summed value for each group.

(Note that you have to coerce the Date object returned by d3.timeDay to a number because maps in JavaScript use simple equality and consider all Date objects to be unequal, even when they represent the same time. This is explained in the d3.rollup notebook I linked.)

Oh, and here’s a notebook demonstrating these approaches:

Thanks a lot!


1 Like