带有 pos & 的 d3.js 条形图每条记录的负条(赢/输) [英] d3.js bar chart with pos & neg bars (win/loss) for each record
问题描述
我想在 d3.js 中制作一个条形图,每个项目或行都有正条和负条,如下所示:
它有点像谷歌金融行业摘要"图表(
如果有一种相对简单的方法来解释如何修改该示例以实现我想要的,那也可以.
谢谢!
我可以这样做:
基础是每个项目有两个值.为简化起见,我们可以说所有值都必须为正值,第一个将显示在右侧,第二个将显示在左侧.
根据您提供的示例,我们将绘制我们添加的第二个值:
data = [{名称:A",值:1,值2:2},...]
我们还将修复域(您可以在之后编写一个函数来很好地完成它):
x.domain([-10,10])
最后,我们将绘制第二个条形(左侧):
svg.selectAll(".bar2").data(数据).enter().append("rect").attr("class", "bar2").attr("x", 函数 (d) {返回 x(Math.min(0, -d.value2));}).attr("y", 函数 (d) {返回 y(d.name);}).attr(宽度",函数(d){返回 Math.abs(x(-d.value2) - x(0));}).attr("高度", y.rangeBand());
此代码只是从我将 d.value
替换为 -d.value1
和 .bar
替换为 的示例中复制粘贴>.bar2
用于类.
您还必须修改 x 轴格式,以获得75、50、25、0、25、50、75".
jsFiddle:http://jsfiddle.net/chrisJamesC/vgZ6E/
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!
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/
这篇关于带有 pos & 的 d3.js 条形图每条记录的负条(赢/输)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!