如何在分组条形图上显示第二个条形图?

时间:2015-07-31 19:18:21

标签: javascript d3.js

我正试图在我的图表中添加第二个条形图。元素正确地被附加但不在正确的位置而不是正确的高度。我希望数据在x轴的1个位置有两个条形,一个高度为2,另一个高度为3,依此类推。

http://jsfiddle.net/626uesbh/4/

var svg2 = d3.select("#histogram").append("svg2")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg2.selectAll(".rect")
      .data(data)
    .enter().append("g")
      .attr("transform", "translate(0, 100)")
    .append("rect")
      .attr("class", "rect")
      .attr("width", 10)
      .attr("height", function(d) { return height - y2Map(d); })
      .attr("x", xMap)
      .attr("y", yMap)
      .style("fill", "blue");

我怀疑svg2转换是问题,但在尝试摆弄它一小时之后我似乎得到了我想要的东西。我看了这个问题并尝试将其实现到我的问题中。 D3.js grouped bar chart

1 个答案:

答案 0 :(得分:1)

Since each element in your data contains the values for both bars, you have to add them as a group. That is, add a 'g' element to the chart for each element in the array, then add a bar for inner_array[1] and inner_array[2].

Hopefully this gets you on the right path, essentially all I changed was the stuff after your //bar comment.

http://jsfiddle.net/626uesbh/6/

  // bar
  var bar_groups = svg.selectAll('.bar-group')
      .data(data)
      .enter().append('g')
      .attr('class', 'bar-group');

  bar_groups.append('rect')
      .attr("class", "rect")
      .attr("width", 10)
      .attr("height", function(d) { return height - yScale(d[1]); })
      .attr("x", function(d) {
          return xScale(d[0]) - 5;
      })
      .attr("y", function(d) {
          return yScale(d[1]);
      })
      .style("fill", "green");

  bar_groups.append('rect')
      .attr("class", "rect")
      .attr("width", 10)
      .attr("height", function(d) { return height - yScale(d[2]); })
      .attr("x", function(d) {
          return xScale(d[0]) + 5;
      })
      .attr("y", function(d) {
          return yScale(d[2]);
      })
      .style("fill", "blue");

Note: there are much more elegant ways to do this. I am only showing you how to add the bars to your existing code. Please take a look at http://bl.ocks.org/mbostock/3887051 for further guidance.