简体   繁体   English

d3分组条形图创建问题

[英]d3 grouped bar chart creation issue

I want to create a grouped bar chart using d3 but all the examples i saw have different data format then mine and i am not able to figure out how to draw the chart using my data format. 我想使用d3创建一个分组的条形图,但是我看到的所有示例都具有与我不同的数据格式,因此我无法弄清楚如何使用我的数据格式绘制该图。

For example: http://bl.ocks.org/mbostock/3887051 例如: http : //bl.ocks.org/mbostock/3887051

Here is my data: 这是我的数据:

var data =[
{
  "data": [
    [
      "2016-01-21T01:20:00.000Z",
      1.41818181818182
    ],
    [
      "2016-01-21T02:28:00.000Z",
      1.90661764705882
    ],
    [
      "2016-01-21T03:36:00.000Z",
      1.66764705882353
    ],
    [
      "2016-01-21T04:44:00.000Z",
      1.51691176470588
    ],
    [
      "2016-01-21T05:52:00.000Z",
      1.40955882352941
    ],
    [
      "2016-01-21T07:00:00.000Z",
      1.46323529411765
    ],
    [
      "2016-01-21T08:08:00.000Z",
      1.48308823529412
    ],
    [
      "2016-01-21T09:16:00.000Z",
      1.89384615384615
    ]
  ],
  "label": "a"
},
{
  "data": [
    [
      "2016-01-21T01:20:00.000Z",
      4.98701298701299
    ],
    [
      "2016-01-21T02:28:00.000Z",
      5.0
    ],
    [
      "2016-01-21T03:36:00.000Z",
      4.94852941176471
    ],
    [
      "2016-01-21T04:44:00.000Z",
      4.91176470588235
    ],
    [
      "2016-01-21T05:52:00.000Z",
      4.81617647058824
    ],
    [
      "2016-01-21T07:00:00.000Z",
      5.0
    ],
    [
      "2016-01-21T08:08:00.000Z",
      4.94117647058824
    ],
    [
      "2016-01-21T09:16:00.000Z",
      4.96969696969697
    ]
  ],
  "label": "b"
}
];

So please help me in creating a grouped bar chart using my data format. 因此,请帮助我使用我的数据格式创建分组的条形图。

Code of what i have written so far: CODE 到目前为止我写过的代码CODE

Instead of this: 代替这个:

   .attr("height", function(d) {
        return y(d[1]); //Note this is returning data
      })

It should be 它应该是

 .attr("height", function(d) {
    return height - y(d[1]); //Note this is returning data
  })

You have not made another scale to position the bars as a result of which the bars were coming one on to of the other. 您尚未制作另一个刻度来放置这些条,因此这些条会彼此叠加。

var x1 = d3.scale.ordinal();
x1.domain(data.map(function(d){return d.label})).rangeRoundBands([0, x.rangeBand()]);

Then in the group you will need to give a transform like this to allign the a bar and b bars: 然后,在该组中,您将需要进行这样的转换以分配a bar和b bar:

  .attr("transform", function(d,i) { 
    var r = parseFloat(x1(d.label));
    if (r == 0){
      r = r-5;
    }
    return "translate(" +  r  + ",0)"; 

  })

Working code here 这里的工作代码

Hope this helps! 希望这可以帮助!

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

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