I'm making a bar chart but I would like the bars not to be too close to each other.
Here is how I define my x scale :
let echelleX = d3.scaleBand()
.domain(setMots)
.range([0, setMots.length * largeurBarre])
.padding(.1);
If I now define my scale with a higher padding :
let echelleX = d3.scaleBand()
.domain(setMots)
.range([0, setMots.length * largeurBarre])
.padding(.5);
Here is the chart I get :
As you can see, only the outer padding changed. According to the d3 API, I'm not doing anything wrong, so I don't see where my mistake is. I looked around StackOverflow and found this fiddle, where changing the padding
values effectively modifies the gap between the bars. What am I missing?
The problem with your code is the fact that you are specifying a hardcoded value for bar widths, instead of relying on dynamically computed value from d3.
Just update the line that specifies the width of your bars to take the value that takes into account the padding that you have specified earlier by means of using echelleX.bandwidth()
:
barre.enter()
.append("rect")
.attr("class", d => d.mot)
.attr("x", (d, i) => echelleX(d.mot))
.attr("y", (d) => echelleY(d.freq))
.attr("width", echelleX.bandwidth()) // <--- this one
.attr("height", d => height - echelleY(d.freq))
.attr("fill", "#ffcc99");
Here is a working fiddle with updates.