begentleimanoob
begentleimanoob

Reputation: 13

D3 is attempting to set attributes of SVG as NaN and I can't figure out why

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):

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:

 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)

Any idea what is going on? Thanks

Upvotes: 1

Views: 101

Answers (1)

Stephen Gilboy
Stephen Gilboy

Reputation: 5825

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

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

is now

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

Upvotes: 3

Related Questions