d3.js bar chart with pos & neg bars (win/loss) for each record

前端 未结 1 1832
情歌与酒
情歌与酒 2020-12-20 04:42

I want to make a bar chart in d3.js that has both positive and negative bars for each item or row, like this:

\"

相关标签:
1条回答
  • 2020-12-20 05:08

    Here is what I could do:

    enter image description here

    The basis is to have two values per item. To simplify things we can say that all values have to be positive, the first one will be displayed on the right, the second one on the left.

    From the example you provided, we will just plot the second value we add:

    data = [
        {name: "A",value: 1,value2: 2},
        ...
    ]
    

    We will also fix the domain (you can write a function to do it nicely afterwards):

    x.domain([-10,10])
    

    Finally, we will draw the second bars (on the left):

    svg.selectAll(".bar2")
        .data(data)
        .enter().append("rect")
        .attr("class", "bar2")
        .attr("x", function (d) {
        return x(Math.min(0, -d.value2));
    })
        .attr("y", function (d) {
        return y(d.name);
    })
        .attr("width", function (d) {
        return Math.abs(x(-d.value2) - x(0));
    })
        .attr("height", y.rangeBand());
    

    This code is just copy paste from the example where I replaced d.value by -d.value1 and .bar by .bar2 for the class.

    You will also have to modify the x-axis format for having "75, 50, 25, 0, 25, 50, 75".

    jsFiddle: http://jsfiddle.net/chrisJamesC/vgZ6E/

    0 讨论(0)
提交回复
热议问题