简体   繁体   English

使用D3.js将条形图分组为“一行”

[英]Grouped bar chart “in one line” with D3.js

I'm trying to make a particular bar chart with D3.js, and I don't find any example who could match. 我正在尝试使用D3.js制作特定的条形图,但找不到任何可以匹配的示例。 I would code a bar chart with two series (one negative, and one generally positive) disposed on the same line, but not stacked. 我会编写一个条形图,在同一条线上放置两个系列(一个为负,一个通常为正),但不要堆叠在一起。

I guess that maybe it's not very clear, so I've made this on Highcharts . 我想可能还不太清楚,所以我在Highcharts上做了这个 I want to use D3 to connect the chart with a map I did before. 我想使用D3将图表与以前做过的地图联系起来。

So, does someone know any example that could help me? 那么,有人知道任何可以帮助我的例子吗? Can I sort directly the chart even if my series are unordered? 即使我的序列是无序的,我也可以直接对图表排序吗? And if the two series are punctually postive, does the little one appear in front of the largest? 如果这两个系列都准时出现,那那个小系列是否出现在最大系列的前面?

The trick is to order your data, in order to do so, you can use the [d3.ascending()][1] functions: 技巧是对数据进行排序,为此,可以使用[d3.ascending()][1]函数:

with the following example data: 带有以下示例数据:

data = [{
    name: "A",
    valueRight: 1,
    valueLeft: 2
}, {
    name: "B",
    valueRight: 4,
    valueLeft: 5
}, ...]

We would have: 我们会有:

function leftBound(node) {
    return d3.max([node.valueLeft,-node.valueRight])
}

function rightBound(node) {
    return d3.max([node.valueRight,-node.valueLeft])
}
dataSort = function(a,b) {
    res = d3.descending(leftBound(a),leftBound(b))
    if(res==0) {
        return d3.descending(rightBound(a),rightBound(b))
    } else {
        return res
    }
}

For reusable charts, you can also use [selection.sort()][2] but you have to do this for the 2 bar categories. 对于可重复使用的图表,您也可以使用[selection.sort()][2]但必须对2个条形类别执行此操作。

JsFiddle: http://jsfiddle.net/vgZ6E/55/ JsFiddle: http : //jsfiddle.net/vgZ6E/55/

ScreenShot: 屏幕截图:

屏幕截图

The original code is from the following question: d3.js bar chart with pos & neg bars (win/loss) for each record 原始代码来自以下问题: d3.js条形图,每条记录具有正负条形(获利/亏损)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM