D3试图将SVG的属性设置为NaN,我无法弄清楚原因

时间:2021-12-28 20:28:29

I'm trying to make some basic d3 charts, which I have a little experience doing. Here is a sample of the JSON I am working with (I have 100 objects, left most out for brevity):

我正在尝试制作一些基本的d3图表,我有一些经验。以下是我正在使用的JSON示例(我有100个对象,为简洁而留下最多):

var data = [
            {
               "OrderID": 1,
               "ShipCountry": "USA",
               "Freight": 168.0,
               "Version": 2
           },
           {
               "OrderID": 2,
               "ShipCountry": "USA",
               "Freight": 336.0,
               "Version": 2
           },
           {
               "OrderID": 3,
               "ShipCountry": "USA",
               "Freight": 504.0,
               "Version": 2
           }]

and here is my d3 code:

这是我的d3代码:

 var margin = { top: 10, bottom: 30, left: 30, right: 20 };

var width = 700 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
//svg for chart with margins
var svg = d3.select('#chart-wrapper')
                .append('svg')
                    .attr('height', height + margin.top + margin.bottom)
                    .attr('width', width + margin.left + margin.right)
                .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

//xScale will be based on orderID attribute
var xScale = d3.scale.linear().domain([0, 99]).range([0, width]);
var yScale = d3.scale.linear().domain([16632, 0]).range(height, 0);




svg.selectAll('circle')
    .data(data)
    .enter()
    .append('circle')
        .attr('cx', function (d) {
            return xScale(d.Freight)
        })
        .attr('cy', function (d) {
            return yScale(d.OrderID);
        })
        .attr('r', 2)
        .attr('fill', 'green');

For some reason, the cy property of each circle gets set to NaN- which obviously keeps it from rendering. I have switched around Freight and OrderID fields, and still only the cy property does not get set correctly. While debugging, I have logged the values of each, and they appear to be real numbers. (This also happened while trying to create a line graph- the second number of the 'd' attribute for my path was NaN, which is when I decided to attempt a scatterplot instead)

出于某种原因,每个圆圈的cy属性被设置为NaN-这显然使其无法渲染。我已经切换了Freight和OrderID字段,但仍然只有cy属性没有正确设置。在调试时,我记录了每个的值,它们看起来是实数。 (这也是在尝试创建折线图时发生的 - 我的路径的'd'属性的第二个数字是NaN,这是我决定尝试使用散点图时)

Any idea what is going on? Thanks

知道发生了什么事吗?谢谢

1 个解决方案

#1


You need to make the argument for .range() an array.

您需要为.range()创建一个数组的参数。

var yScale = d3.scale.linear().domain([16632, 0]).range(height, 0);

is now

var yScale = d3.scale.linear().domain([16632, 0]).range([height, 0]);

#1


You need to make the argument for .range() an array.

您需要为.range()创建一个数组的参数。

var yScale = d3.scale.linear().domain([16632, 0]).range(height, 0);

is now

var yScale = d3.scale.linear().domain([16632, 0]).range([height, 0]);