I'm trying to convert my csv to the format needed by nvd3's stacked area chart: http://nvd3.org/ghpages/stackedArea.html but got lost in the arrays conversion. Can someone help?
csv: length,m1,m2,m3,m4 9,1,2,3,4 99,11,22,33,44 999,111,222,333,444
format needed by nvd3
var histcatexplong = [ { "key" : "Consumer Discretionary" , "values" : [ [ 0000000000000 , 27.38478809681] , [ 0000000000000 , 27.371377218208] , [ 0000000000000 , 26.823411519395] } , { "key" : "Consumer Staples" , "values" : [ [ 0000000000000 , 27.45458809681] , [ 0000000000000 , 27.444444444408] , [ 0000000000000 , 26.455555555395] } ,
so if the conversion is right, I should get: var myall = [ { "key" : "m3" , "values" : [ [ 9 , 3] , [ 99, 33] , [ 999, 333] } , { "key" : "m1" , "values" : [ [ 9 , 1] , [ 99, 11] , [ 999, 111] } ,
My code for the conversion:
d3.csv("s1.csv", function (csv) {
var myall = [
{
"key" : "m3",
"values" : []
},
{
"key" : "m2",
"values" : []
}
];
v3 = csv.map(function(d) { return [ +d["length"], +d["m3"] ]; });
v2 = csv.map(function(d) { return [ +d["length"], +d["m2"] ]; });
d3.keys(csv).forEach(function(d) {
myall[0].values.push(v3);
myall[1].values.push(v2);
});
console.log(myall);
The problem is that myall didn't show up in the DOM (console output seems to be missing a top hierarchy:
[Object { key="m345", values=[249]}, Object { key="m2", values=[249]}]
For the nvd3 stacked area chart example, DOM copy/paste for the histcatexplong var:
*histcatexplong
[Object { key="Consumer Discretionary", values=[77]}, Object { key="Consumer Staples", values=[77]}, Object { key="Energy", values=[77]}, 7 more...]*
Thanks.
After some debugging, I fixed the issue. As a help to fellow learners, I post the code. This is useful for people that need: a. nvd3 stacked area chart(gives you the tooltips and other utilities for free i.e. no extra programming) b. x-axis with values instead of dates c. has csv data (flat hierarchy) in this format:
code (modified from http://nvd3.org/ghpages/stackedArea.html):