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?
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?
Share Improve this question edited May 24, 2014 at 21:19 Kyle Brandt asked May 24, 2014 at 21:09 Kyle BrandtKyle Brandt 28.6k39 gold badges127 silver badges172 bronze badges 3-
I'm guessing that
yScale(d)
ish/2
. In general, these variants won't give you the same result. – Lars Kotthoff Commented May 24, 2014 at 21:12 - 1 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 Commented May 24, 2014 at 21:22
- 1 @LarsKotthoff: Made an answer, it seems the former plays better with the yAxis function – Kyle Brandt Commented May 24, 2014 at 21:46
1 Answer
Reset to default 5Now 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 es out as follows (with no transforms of the yAxis call:
Which generally is not what one would want.