> For example, this data should give the y value corresponding to x = i:
> var posdata = [3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 7]
>
> but this data should be passed to a color interpolating scale to
> determine the color of the segment from x = i to x = i+1:
> var coldata = [1, 2, 3, 4, 7, 6, 8, 9, 8, 7, 6, 5, 3]
>
> I think I can do this by creating a separate d3.svg.line(), and
> corresponding path, for each segment of my chart;
> is there any easier way?
You should just need one d3.svg.line(), used like this:
var colorscale = d3.scale.category20c();
d3.svg.line().y(function(d, i) { return posdata[i]; })
.attr("stroke", function(d, i) { return colorscale(coldata[i]); });
Lars
You can't set .attr() on d3.svg.line(), set it on the element you're
drawing instead:
var line = d3.svg.line()
.x(function(d, i) { return i; })
.y(function(d, i) { return d; }),
colorscale = d3.scale.category20c();
svg.selectAll("path")
.data(posdata).enter()
.append("svg:path")
.attr("stroke", function(d, i) { return colorscale(coldata[i]); })
.attr("d", line);
You could also use svg:line elements instead of svg:path but this is probably
easier.
Lars
Yes, if you use svg:path, the colour will be the same -- to get a different
colour for each segment you would have to use different svg:paths or svg:lines.
Sorry, I shouldn't post examples without actually trying them -- you're right,
this one doesn't work as intended. Something like this gives you line segments
with different colours:
vis.selectAll("line")
.data(posdata)
.enter().append("svg:line")
.attr("x1", function(d, i) { return i; })
.attr("x2", function(d, i) { return i+1; })
.attr("y1", function(d, i) { return posdata[i]; })
.attr("y2", function(d, i) { return posdata[i+1]; })
.attr("fill", "none")
.attr("stroke", function(d, i) { return colorscale(coldata[i]); });
I'm setting the coordinates explicitly here, but you can also use the previous
approach with d3.svg.line() and svg:path. The only difference is that then you
would need to transform the data into a matrix with two columns in each row for
the coordinates to connect.
Lars