JPC*_*JPC 5 javascript css jquery d3.js
如果X> 100,我想改变此折线图的颜色我希望它变成"红色"
有没有办法可以根据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");
Run Code Online (Sandbox Code Playgroud)

这是另一种方式,也许在某些情况下可能有所帮助:
我所做的就是使用以下方法分割数据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");
Run Code Online (Sandbox Code Playgroud)
我认为您可以通过为线条定义渐变而不是样式来实现这一点。在此处查看此解决方案。 根据数据更改折线图的颜色(红色表示高于阈值 0 ,蓝色表示低于 0)
我昨天问了一个非常相似的问题,并且能够通过阅读 D3 文档并查看一些这样的示例来使其工作 https://bl.ocks.org/mbostock/3970883
svg.append("linearGradient")
.attr("id", "line-gradient")
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", 0).attr("y1", y(0))
.attr("x2", 0).attr("y2", y(2))
.selectAll("stop")
.data(
[
{offset: "100%", color: "blue"},
{offset: "100%", color: "red"},
]
)
.enter().append("stop")
.attr("offset", function(d) { return d.offset; })
.attr("stop-color", function(d) { return d.color; });
Run Code Online (Sandbox Code Playgroud)