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" });
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" });
Is either one more correct, if so, why?
yScale(d)
ish/2
. In general, these variants won't give you the same result. – Lars Kotthoff