画一条直线D3.js

时间:2014-08-01 14:31:11

标签: javascript d3.js

我觉得这有一个非常简单的解决方案,但我现在已经挣扎了一段时间。我有一个d3折线图,我想在图表上画一条代表数据平均值的线。我试图用line属性做这个,但我一直得到相同的错误。我一直遇到的错误是:

"意外值NaN解析y1属性。 意外值NaN解析y2属性。 "

以下是我尝试绘制线条的代码:

student_av_data.forEach(function(d) { 
     d.student_average = +d.student_average; 
     });

svg.append("line")
    .style("stroke", "orange")
    .style("opacity", 1)
    .attr("x1", 0)
    .attr("y1", y0(function(d) {return y0(d.student_average);}))
    .attr("x2", width)
    .attr("y2", y0(function(d) {return y0(d.student_average);}));

function(d) {return y0(d.student_average);}应该只是一个数字,应该在y0参数中有用。

不确定是什么问题。任何建议,将不胜感激。谢谢!

编辑:

作为参考,这是有效的,基本上是我尝试做的,但在d.student_average中使用y0()

svg.append("line")
    .style("stroke", "black")
    .style("opacity", .2)
    .attr("x1", 0)
    .attr("y1", y0(24))
    .attr("x2", width)
    .attr("y2", y0(24));

1 个答案:

答案 0 :(得分:2)

尝试替换为:

 svg.append("line")
        .style("stroke", "orange")
        .style("opacity", 1)
        .data(student_av_data)
        .attr("x1", 0)
        .attr("y1", function(d) {return y0(d.student_average);})
        .attr("x2", width)
        .attr("y2", function(d) {return y0(d.student_average);});

将从数据元素中获取d