I\'m making a bar chart with the following code:
svg.selectAll(\".bar\")
.data(data)
.enter().append(\"rect\")
.attr(\"class\", \"bar\")
.attr(\"
Why is this happening?
The way that this is set up means that you're setting the top of the rect
to be at whatever y-value relates to d.frequency
, and then defining the bottom to be on the x-axis itself (by subtracting the calculated y-value from the max height). Given that before the transition you're effectively fixing the y-value, then getting the height to transition, what you're actually doing is just moving the bottom of the rect
, giving the effect you describe.
How can I fix this?
The simplest fix is to transition both the y-value and the height, in a manner that keeps the bottom of the rect
fixed. To do this, before the transition simply set the y
attr to be y(0)
, then after the transition()
, set the y
attr to be the calculated version, i.e. y(d.frequency)
. Like so:
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.value) - barWidth / 2;
})
.attr("width", barWidth)
.attr("y", function(d) {
return y(0);
})
.attr("height", 0)
.transition()
.attr("y", function(d) {
return y(d.frequency);
})
.attr("height", function(d) {
return height - y(d.frequency);
});