【问题标题】:d3js v4 Overlapping Bar Chartd3js v4 重叠条形图
【发布时间】:2018-04-16 16:24:10
【问题描述】:

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

如何更新 d3js v4 的示例?

当我添加第二个栏时出现了我的问题。 这是我的示例(正在进行中),有关数据,请参见示例 1。

<!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>

谢谢!

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    你只需要添加两个栏:

    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

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多