Stacked area in D3.js

I am using D3.js and I am having problems setting up a complex layout for an area chart with multiple series. I have two possible structures for my data (if that helps). One of them is the initial data supplied to the script in this structure:

var data = [{key: 'Group1', value: 37, date: '04/23/12'}, {key: 'Group2', value: 12, date: '04/23/12'}, {key: 'Group3', value: 46, date: '04/23/12'}, {key: 'Group1', value: 32, date: '04/24/12'}, {key: 'Group2', value: 19, date: '04/24/12'}, {key: 'Group3', value: 42, date: '04/24/12'}, {key: 'Group1', value: 45, date: '04/25/12'}, {key: 'Group2', value: 16, date: '04/25/12'}, {key: 'Group3', value: 44, date: '04/25/12'}, {key: 'Group1', value: 24, date: '04/26/12'}, {key: 'Group2', value: 52, date: '04/26/12'}, {key: 'Group3', value: 64, date: '04/26/12'}] 

The second is a nested structure created using this code:

  pData = d3.nest() .key(function(d) { return d.key; }) .map(data); 

The result in this structure:

 pData = {Group1: [{date: 04/23/12, key: "Group1", value: 37}, {date: 04/24/12, key: "Group1", value: 32}, {date: 04/25/12, key: "Group1", value: 45}, ...], Group2: [{date: 04/23/12, key: "Group2", value: 12}, {etc, etc, etc}], GroupX: [...] } 

My questions . How to set up the d3.layout.stack() generator using one of the above data structures (or some options) to create a complex structure for my data so that I can go through this to an area generator like this:

 var areaGenerator = d3.svg.area() .interpolate('monotone') .x(function(d) { return x(d.date); }) .y0(h) .y1(function(d) { return y(d.value); }); 
+7
source share
1 answer

You must feed the array of layers into the stack layout, so the first thing to change is to use nest.entries , not nest.map . This returns an array of objects with a key field (for example, "Group1") and an values array that contains related records. Then you specified stack.values so that the stack layout could access the values array for each level.

You will also need to determine the appropriate x and y accessors for the stack layout so that it can understand your input: x-accessor should return d.date , and y-accessor should return d.value . You will also need to convert your date strings to Dates; you can use d3.time.format to help with this. For example:

 var format = d3.time.format("%m/%d/%y"); data.forEach(function(d) { d.date = format.parse(d.date); }); 

Finally, change the definition of your area so that the base line y0 is defined as y(d.y0) and the top line y1 is defined as y(d.y0 + dy) .

Here is a working example:

+12
source

All Articles