Juan Juan - 1 month ago 8
Javascript Question

D3.js: Scale for circle radius is not displaying the circles

I have created two scales for the x and y and both are working. Now when I try to do the same with the radius of the circles it doesn't show them, and it doesn't throw any error either.....What could be the problem. The codepen is the following: http://codepen.io/juanf03/pen/rrKxgd

var
dataset = [
[ 5, 20 ],
[ 480, 90 ],
[ 250, 50 ],
[ 100, 33 ],
[ 330, 95 ],
[ 410, 12 ],
[ 475, 44 ],
[ 25, 67 ],
[ 85, 21 ],
[ 220, 88 ]
];
var h=300,w=500;
var padding = 20;
var
xScale = d3.scaleLinear().domain([0, d3.max(dataset,
function(d) { return d[0]; })]).range([padding, w-padding*2]);

var yScale= d3.scaleLinear()
.domain([0,d3.max(dataset,function(d){
return d[1];
})]).range([h-padding,padding]);

var
rScale = d3.scaleLinear() .domain([0, d3.max(dataset,
function(d) {
return
d[1]; })]).range([2, 5]);

var svg=d3.select("body")
.append("svg")
.attr("width",w)
.attr("height",h);

svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx",function(d){
return xScale(d[0]);
}).attr("cy",function(d){
return yScale(d[1]);
}).attr("r",function(d,i){
return rScale(d[1]);
});

svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d){
return `${d[0]} , ${d[1]}`;
}) .attr("x", function(d) {
return xScale(d[0]);})
.attr("y", function(d) {
return yScale(d[1]);})
.attr("font-family", "sans-serif")
.attr("font-size","11px")
.attr("fill","red");


var
xAxis = d3.svg.axis() .scale(xScale) .orient("bottom");

svg.append("g")
.call(xAxis);

Answer

Inspect your console: you have a lot of NaN. And they come from your rScale.

This is the problem: in JavaScript, a return statement followed by a line break tells the browser that a semi colon should be inserted after that return. So, when you write:

var rScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function(d) {
        return 
            d[1]; })])
    .range([2, 5]);

You are actually writing:

return;
    d[1];

I did only one thing: just deleted the new line:

return d[1];

Here is your codepen: http://codepen.io/anon/pen/yaEwZW?editors=1010