如何根据轴值更改d3js中的线条颜色? [英] How to change line color in d3js according to axis value?
本文介绍了如何根据轴值更改d3js中的线条颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果X> 100,我希望更改此折线图的颜色,我希望它变为红色"
I want to change color for this line chart if X > 100 I want it to turn "red"
有没有一种方法可以基于X的值在笔触颜色样式中使用条件?
Is there a way I can use condition within stroke color style based on value of X ?
http://jsfiddle.net/iamjeannie/b445svob/1/ 在此处输入链接描述
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);
//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
推荐答案
这是另一种方式,也许在某些情况下可能会有所帮助:
Here's another way, maybe in some instances that might help:
我要做的就是使用filter
拆分数据:
All I do is split the data by using a filter
:
var lineGraph1 = svgContainer.append("path")
.attr("d", lineFunction(lineData.filter(function(d) {
return d.x <= 100;
})))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
var lineGraph2 = svgContainer.append("path")
.attr("d", lineFunction(lineData.filter(function(d) {
return d.x >= 100;
})))
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("fill", "none");
这篇关于如何根据轴值更改d3js中的线条颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文