I created a multiple-line chart using nvd3, but was unable to modify it in some important ways. I would like to roll my own using straight d3js, but I'm struggling with thinking in joins.
I need to create a path for each d.key
with its own corresponding d.values
.
My data is formatted for nvd3 as follows (abridged).
[
{
"key":"brw-a",
"values":[
["2012-07-11T00:00:00", 0.0 ],
["2012-07-11T23:59:59", 0.0 ],
["2012-07-05T06:31:47", 0.0 ],
["2012-07-05T23:59:59", 0.0 ]
]
},
{
"key":"brw-c",
"values":[
["2012-07-11T00:00:00", 0.0 ],
["2012-07-07T00:00:00", 2.0 ],
["2012-07-05T23:59:59", 4.0 ]
]
}
]
I seem to need an inner loop to access the array stored in each d.values
. I have a working example that demonstrates how d.values
comes out in one big glob of uselessness.
var p = d3.select("body").selectAll("p")
.data(data)
.enter().append("p")
.text(function(d) {return d.key +": " + '[' + d.values + ']'})
I feel like I'm close, and it has something to do with:
.data(data, function(d) { return d.key; })
Update: I was able to manually loop over the data to create the desired effect. Perhaps there is not a way of doing this with joins? Save for using the wonderful nvd3 lib, of course. See the comment below for the link.
var body = d3.select("body")
for (i=0; i < data.length; i++) {
var key = data[i].key
var values = data[i].values
body.append("h3")
.text(key)
for (j=0; j < values.length; j++) {
body.append("p")
.text(values[j][0] + " -- " + values[j][1])
}
}
You were right about .data()
function. But because you need to loop through elements in values
, that's what you need to pass as data for a nested selection:
.data(function(d) { return d.values})
You could try this:
var p = d3.select("body").selectAll("p")
.data(data)
.enter().append("p")
.attr("id", function(d) { return d.key})
.text(function(d) {return d.key})
.selectAll("span")
.data(function(d) { return d.values})
.enter().append("span")
.text(function(d) {return d})
Produces:
<p id="brw-a">brw-a
<span>2012-07-05T00:00:00,0</span>
<span>2012-07-06T23:59:59,1</span>
<span>2012-07-07T06:31:47,0</span>
<span>2012-07-08T23:59:59,3</span>
</p>
<p id="brw-c">brw-c
<span>2012-07-11T00:00:00,0</span>
<span>2012-07-07T00:00:00,2</span>
<span>2012-07-05T23:59:59,4</span>
</p>