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

2020-02-13 01:49发布

问题:

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

it's somewhat like the google finance "Sector Summary" chart (http://google.com/finance)

Can anyone point me to a d3.js example of this kind of chart? I am aware of the "bar chart with negative values" example here: http://bl.ocks.org/mbostock/2368837

If there is a relatively easy way to explain how to modify that example to accomplish what I want, that could work too.

Thanks!

回答1:

Here is what I could do:

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/