简体   繁体   中英

d3js v4 Overlapping Bar Chart

I become frustrated because I can't achieve my task (I am a beginner in d3). I want to overlap my bar chart (here the example1 in d3js v3 ( http://plnkr.co/edit/wfOx8615PnZh2CST301F?p=preview ).

How update the example for d3js v4 ?

My problem occurs when I add the second bar. Here my example (in progress), for data see the 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>

Thank you!

You just need to add both bars:

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());

And the relevant CSS:

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

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

Updated plunker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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