1
votes

I'm learning D3, and I can see that I get the same visualization with these two things:

var w = 600;
var h = 100;

var dataset = [1, 6, 3, 4, 10, 4, 9]

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

var xScale = d3.scale.linear()
    .domain([0, dataset.length])
    .range([0, w]);

Using the height attribute:

 
var yScale = d3.scale.linear()
    .domain([0, d3.max(dataset)])
    .range([h, 0]);

svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr({
        x: function(d, i) { return xScale(i); },
        y: function(d) { return yScale(d); },
        width: w / dataset.length,
        height: function(d) { return h - yScale(d); },
        fill: "teal"
    });

enter image description here

Or setting y:

var yScale = d3.scale.linear()
    .domain([0, d3.max(dataset)])
    .range([0, h]);

svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr({
        x: function(d, i) { return xScale(i); },
        y: function(d) { return h - yScale(d); },
        width: w / dataset.length,
        height: function(d) { return yScale(d); },
        fill: "teal"
    });

enter image description here

Is either one more correct, if so, why?

1
I'm guessing that yScale(d) is h/2. In general, these variants won't give you the same result.Lars Kotthoff
Oh right, you've swapped the range endpoints. Yeah, this will give you identical results. No difference -- really up to you what you prefer.Lars Kotthoff
@LarsKotthoff: Made an answer, it seems the former plays better with the yAxis functionKyle Brandt

1 Answers

5
votes

Now that I got to a later chapter, it seems like former option, which uses range([h, 0]) is better when creating a yAxis. If I use the latter option range([0, h]), the graph comes out as follows (with no transforms of the yAxis call:

enter image description here

Which generally is not what one would want.