javascript - 如何根据轴值更改 d3js 中的线条颜色?

标签 javascript jquery css d3.js

如果 X > 100,我想更改此折线图的颜色 我希望它变成“红色”

有没有一种方法可以根据 X 的值在笔触颜色样式中使用条件?

http://jsfiddle.net/iamjeannie/b445svob/1/ enter link description here

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");

enter image description here

最佳答案

这是另一种方式,也许在某些情况下可能会有所帮助:

我所做的就是使用 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");

关于javascript - 如何根据轴值更改 d3js 中的线条颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026625/

相关文章:

javascript - JQuery动态加载Javascript文件

javascript - 将选项卡更改为 Accordion - 单击时 Accordion 菜单不会折叠

javascript - 这个跨度如何在选择框中不可见?

javascript - 当用户在 Javascript 中使用鼠标滚轮开始滚动时,如何确定用户将滚动多少像素

javascript - 查找数组中最长的单词 JavaScript

javascript - 通过 state.value ReactJS 将 textarea 值复制到新组件

javascript - 无法在桌面上为远程 IP 文件创建快捷方式

jquery - 使用 JQuery,如何根据另一个元素的名称选择一个元素?

Javascript 性能 - 迭代 dom 并添加监听器

javascript - 需要比特币校验地址和 json 帮助