Upgrading the d3.js stack layout from v3 to v4

Using D3 v3, I formatted my data to fit Mike's example in order to quickly start my dev process. Example here https://github.com/d3/d3-3.x-api-reference/blob/master/Stack-Layout.md

var data = [ { "name": "apples", "values": [ { "x": 0, "y": 91}, { "x": 1, "y": 290} ] }, { "name": "oranges", "values": [ { "x": 0, "y": 9}, { "x": 1, "y": 49} ] } ]; 

Then all I had to do to get the values โ€‹โ€‹stacked was

 var stack = d3.layout.stack().values(d=>d.values) var layers = stack(data) 

Exactly how he did it in his example.

However, in v4, it seems that the stack function expects tabular formatted data, so the data above will look like this.

 var data = [ {x: 0, apples: 91, oranges: 9}, {x: 1, apples: 290, oranges: 49}, ]; 

Is there an easy way to save the data format and use the v4 stack function? I can't seem to figure out how to do this. In my current data format, I have useful properties related to an array of values. If I change my data format to tables, I donโ€™t see a convenient way to connect properties with values.

+3
source share
1 answer

I have the same problem. Unfortunately, the new way does not seem to match the way the APIs serialize model instances (like your source data); instead, you are stuck in the JSONified table data format. I feel this works when you work with csv dumps, but thatโ€™s not how the databases are organized.

I posted a related answer here that converts a format grouped by objects (e.g., by fruit in your example) into a data format (using the x-coordinate in your example) as d3.stack() expected. You will be able to adapt the code to your specific case.

0
source

All Articles