Reputation: 2725
I am learning d3 js. I found a great book about the library. But I needed to translate the code examples from version 3 to 4. Here is my code on version 4
<body>
<script type="text/javascript">
var width = 800;
var height = 500;
var dataset = [];
dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([0, width], 0.5);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([0, height]);
var svg = d3.select("body")
.append("svg")
.attr("width",width)
.attr("height",height);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i){return xScale(i);})
.attr("y", function(d){return height- yScale(d);})
.attr("width", xScale.bandwidth())
.attr("height", function(d){return yScale(d);})
.attr("fill", function(d){return "rgb(0,0,"+d*10+")";});
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d){return d;})
.attr("text-anchor", "middle")
.attr("x", function(d, i){return xScale(i) + xScale.bandwidth() / 2;})
.attr("y", function(d){return height - yScale(d) + 14;})
.attr("fill", "white");
</script>
</body>
As I understand, this
.rangeRound([0, width], 0.5);
should bring some gaps between the bars. But, I don’t' know why - there are no gaps! What am I doing wrong?
Upvotes: 1
Views: 2519
Reputation: 1529
I believe the new pattern in d3 v4 would be -
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([0, width])
.paddingInner(0.05);
Upvotes: 4