d3 startAngle是NaN,endAngle是NaN,它会抛出错误

时间:2015-07-28 13:38:41

标签: javascript d3.js

我有一个由以下数据组成的数据集:

    {   
        current: 5
        expected: 8
        gap: -3
        id: 3924
        name: "Forhandlingsevne"
        progress: "0"
        type: 2
    }

现在我有以下JavaScript代码:

    var data = scope.dataset;
var width = 500,
    height = 500,
    radius = Math.min(width, height) / 2,
    innerRadius = 0.3 * radius;

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.width; });

var tip = d3.tip()
    .attr('class', 'd3-tip')
    .offset([0, 0])
    .html(function(d) {
        return d.data.name + ": <span style='color:orangered'>" + d.data.current + "</span>";
    });

var arc = d3.svg.arc()
    .innerRadius(innerRadius)
    .outerRadius(function (d) {
        return (radius - innerRadius) * (d.data.current / 100.0) + innerRadius;
    });

var outlineArc = d3.svg.arc()
    .innerRadius(innerRadius)
    .outerRadius(radius);

var svg = d3.select("#astroD3").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg.call(tip);


    // for (var i = 0; i < data.score; i++) { console.log(data[i].id) }

    var path = svg.selectAll(".solidArc")
        .data(pie(data))
        .enter().append("path")
        .attr("fill", function(d) { return getColor(d.gap); })
        .attr("class", "solidArc")
        .attr("stroke", "gray")
        .attr("d", arc)
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide);

    var outerPath = svg.selectAll(".outlineArc")
        .data(pie(data))
        .enter().append("path")
        .attr("fill", "none")
        .attr("stroke", "gray")
        .attr("class", "outlineArc")
        .attr("d", outlineArc);


    // calculate the weighted mean score
    var score =
        data.reduce(function(a, b) {
            //console.log('a:' + a + ', b.score: ' + b.score + ', b.weight: ' + b.weight);
            return a + (b.current * b.expected);
        }, 0) /
        data.reduce(function(a, b) {
            return a + b.expected;
        }, 0);

    svg.append("svg:text")
        .attr("class", "aster-score")
        .attr("dy", ".35em")
        .attr("text-anchor", "middle") // text-align: right
        .text('');


function getColor(gap)
{
    return gap > 0 ? '#5cb85c' : '#d9534f';
}

运行时,我得到多个错误(我的数据集中的每个数据都有1个)说:

Error: Invalid value for <path> attribute d="MNaN,NaNA85.5,85.5 0 1,1 NaN,NaNLNaN,NaNA75,75 0 1,0 NaN,NaNZ"

当我调试时,我可以看到我的变量看起来像这样:

Object {data: Object, value: NaN, startAngle: NaN, endAngle: NaN}

所以我的问题是我做错了什么?

1 个答案:

答案 0 :(得分:1)

You're telling D3 to use the attribute width to determine the pie slices -- this attribute doesn't exist in your data. It looks like you want

var pie = d3.layout.pie()
  .sort(null)
  .value(function(d) { return d.current; });