D3 bar chart not showing first element in array

前端 未结 1 1441
醉话见心
醉话见心 2021-01-20 21:10

I\'m working on the first set of D3 tutorials (found here) and have run into a problem where the first item of the data array doesn\'t appear. The border i have placed on ea

相关标签:
1条回答
  • 2021-01-20 21:57

    You have this in your HTML:

    <div class="project">
      <div class="project__bar-chart"></div>
    </div>
    

    Thus, when you do:

    d3.select(".project").selectAll(".project__bar-chart")
    

    You are selecting one previously existing <div> in your selectAll, and your "enter" selection will have one element less.

    Solution: remove the div with class project__bar-chart:

    <div class="project">
        //look Ma, no div
    </div>
    

    Here is your Pen: https://codepen.io/anon/pen/bgKxXG?editors=1010

    And here is a Stack snippet:

    var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ]; //The data that we're working with
    
    d3.select(".project") //bring our focus to the container containing this class
      .selectAll(".project__bar-chart")
        .data(data) //the data is in line 1 
      .enter()
      .append("div") // Shove the data (defined in line 1) into the Div in the HTML
        .attr("class", "project__bar-chart")
        .style("width", function(d) {return d + "rem";}) 
    //we're inserting a function in this style attribute to make sure that the width of the div reflects the value given. 
        .text(function(d) {return d;}) //this is what it will look like
    .project {
      color: black;
        font: 1rem;
        font-family: sans-serif;
        margin: .1rem:;
        text-align: right;
    }
    
    .project__bar-chart {
        background: #be3c3c;
        border: 1px solid #802828
        }
      <head>
        <script src="https://d3js.org/d3.v4.js"></script>
        <script type="text/javascript" src="index.js"></script>
      </head>
      <body>
        <div class="project">
        </div>

    0 讨论(0)
提交回复
热议问题