Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

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

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

enter image description here

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

enter image description here

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...