Height transitions go from top down, rather than from bottom up in D3

后端 未结 4 2047
旧巷少年郎
旧巷少年郎 2021-02-09 02:54

I\'m making a bar chart with the following code:

svg.selectAll(\".bar\")
    .data(data)
    .enter().append(\"rect\")
    .attr(\"class\", \"bar\")
    .attr(\"         


        
4条回答
  •  深忆病人
    2021-02-09 03:31

    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);
        });
    

提交回复
热议问题