I want to change color for this line chart if X > 100 I want it to turn \"red\"
Is there a way I can use condition within stroke color style based on value of X ?
Here's a quick example that I've come up with:
Instead of a single path, let's use multiple lines.
We'll need to convert our data to have the following properties:
[
{
x1: currentX,
y1: currentY,
x2: nextX,
y2: nextY
},
...
]
Then we can draw them with a conditional stroke attribute based on data:
var lines = svgContainer.selectAll('line')
.data(lineData)
.enter()
.append('line')
.attr('x1', function(d) { return d.x1; })
.attr('y1', function(d) { return d.y1; })
.attr('x2', function(d) { return d.x2; })
.attr('y2', function(d) { return d.y2; })
.attr("stroke", function (d) {
return (d.x > 50) ? 'red' : 'blue';
})
.attr("fill", "none")
.attr("stroke-width", 2);
Here's a demo:
var lineData = [
{"x": 1, "y": 5},
{"x": 20, "y": 20},
{ "x": 40, "y": 10}, { "x": 60, "y": 40},
{ "x": 80, "y": 5}, { "x": 100, "y": 60},
{ "x": 120, "y": 15}, { "x": 140, "y": 40},
{ "x": 160, "y": 25}, { "x": 180, "y": 20},
{ "x": 200, "y": 15}, { "x": 220, "y": 80},
{ "x": 240, "y": 35}, { "x": 260, "y": 60}
];
//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//The SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);
lineData = lineData.map(function (point, index, arr) {
var next = arr[index + 1],
prev = arr[index - 1];
return {
x: point.x,
y: point.y,
x1: point.x,
y1: point.y,
x2: (next) ? next.x : prev.x,
y2: (next) ? next.y : prev.y
};
});
var lines = svgContainer.selectAll('line')
.data(lineData)
.enter()
.append('line')
.attr('x1', function(d) { return d.x1; })
.attr('y1', function(d) { return d.y1; })
.attr('x2', function(d) { return d.x2; })
.attr('y2', function(d) { return d.y2; })
.attr("stroke", function (d) {
return (d.x > 50) ? 'red' : 'blue';
})
.attr("fill", "none")
.attr("stroke-width", 2);