Reputation: 4035
I'm trying to make some lines with this data format:
var data3 = [
{ "task": "Estructura", "data": [{"x":new Date(Date.parse("2014-01-03")),"y":0}, {"x":new Date(Date.parse("2014-03-09")),"y":8}] },
{ "task": "Mamposteria", "data": [{"x":new Date(Date.parse("2014-02-01")),"y":0}, {"x":new Date(Date.parse("2014-03-01")),"y":8}] },
{ "task": "Friso", "data": [{"x":new Date(Date.parse("2014-03-01")),"y":0}, {"x":new Date(Date.parse("2014-03-30")),"y":8}] },
{ "task": "Mortero", "data": [{"x":new Date(Date.parse("2014-05-01")),"y":8}, {"x":new Date(Date.parse("2014-07-01")),"y":0}] },
{ "task": "Pisos", "data": [{"x":new Date(Date.parse("2014-07-01")),"y":8}, {"x":new Date(Date.parse("2014-09-01")),"y":0}] }
];
And this the code for generating the lines:
var colors = [
'steelblue',
'green',
'red',
'purple',
'black'
]
var xScale = d3.time.scale()
.domain([
new Date(Date.parse('2014-01-01')),
new Date(Date.parse('2014-12-31'))
])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, 8])
.range([height, 0]);
var line = d3.svg.line() // line generator
.interpolate("linear")
.x(function(d) { return xScale(d.data.x); })
.y(function(d) { return yScale(d.data.y); });
var activities = svg.selectAll('.line')
.data(data3)
.enter()
.append("path");
var activitiesAttibutes = activities
.attr("class", "line")
.attr('stroke', function(d,i){
return colors[i%colors.length];
})
.attr("d", line)
.attr("transform", "translate(15,30)");
but I'm having trouble because it is not a two element array.
Do I have to arrange the data in another way or make changes in the line function generator? Could you provide me an example where I can solve this?
Upvotes: 0
Views: 23
Reputation: 55688
There are two things that need to change here - you need to iterate over the data
array in each object for the line, and you need to change the accessors so that they apply to a single object in the data
array:
var line = d3.svg.line() // line generator
.interpolate("linear")
// d is a single object in a data array
.x(function(d) { return xScale(d.x); })
.y(function(d) { return yScale(d.y); });
and then to apply the line, you're acting on a top-level object, so you need to pass in the data
array:
var activitiesAttibutes = activities
.attr("d", function(d) {
return line(d.data);
});
See fiddle: http://jsfiddle.net/h07s5jc5/1/
Upvotes: 1