d3js v4重叠条形图

时间:2018-04-16 16:24:10

标签: javascript d3.js

我变得沮丧,因为我无法完成任务(我是d3的初学者)。 我想重叠我的条形图(这里是d3js v3中的example1(http://plnkr.co/edit/wfOx8615PnZh2CST301F?p=preview)。

如何更新d3js v4的示例?

添加第二个栏时出现问题。 这里我的示例(正在进行中),数据参见example1。

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
</head>

<style>

  .bar {
    fill: steelblue;
  }
  .x_axis path {
    display: none;
  }

</style>

<body>
  <svg width="660" height="700" viewBox="0 0 660 700" class="my_bar"></svg>

  <script>

  let svg = d3.select(".my_bar")

  let margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = +svg.attr("width") - margin.left - margin.right,
      height = +svg.attr("height") - margin.top - margin.bottom;

  let x = d3.scaleLinear().rangeRound([0, width]);
  let y = d3.scaleBand().rangeRound([0,height]).padding(0.1);

  let g = svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  d3.csv("data.csv", function(error, data) {
    if (error) throw error;
    console.log(data);

    x.domain([0, d3.max(data, function(d) { return d.col1; })]);
    y.domain(data.map(function(d) { return d.letter; }));


  g.append("g")
      .attr("class", "axis x_axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));


  g.append("g")
      .attr("class", "axis y_axis")
      .call(d3.axisLeft(y));


  g.selectAll(".bar")
    .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", 0)
      .attr("y", function(d) { return y(d.letter); })
      .attr("width", function(d) { return x(d.col1); })
      .attr("height", y.bandwidth());
});
  </script>

</body>
  </html>

谢谢!

1 个答案:

答案 0 :(得分:2)

您只需添加两个栏:

g.selectAll(".bar1")
    .data(data)
    .enter().append("rect")
      .attr("class", "bar1")
      .attr("x", 0)
      .attr("y", function(d) { return y(d.letter) + 10; })
      .attr("width", function(d) { return x(d.col1); })
      .attr("height", y.bandwidth() - 20);

 g.selectAll(".bar2")
    .data(data)
    .enter().append("rect")
      .attr("class", "bar2")
      .attr("x", 0)
      .attr("y", function(d) { return y(d.letter); })
      .attr("width", function(d) { return x(d.col2); })
      .attr("height", y.bandwidth());

相关的CSS:

.bar1 {
    fill: steelblue;
    opacity: 0.5;
  }

  .bar2 {
    fill: gray;
    opacity: 0.5;
  }

更新了plunker