Libby B Libby B - 4 years ago 112
CSS Question

D3 bar chart not showing first element in array

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 each data div element indicates that essentially that first entry has "collapsed" into a line up the top. Is there an explanation as to why this is happening? How can I fix this?

My HTML, CSS and JS has been put onto codepen to view and edit.

Thanks in advance!

Isolated JS:

var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ];

d3.select(".project")
.selectAll(".project__bar-chart")
.data(data)
.enter()
.append("div")
.attr("class", "project__bar-chart")
.style("width", function(d) {return d + "rem";})
.text(function(d) {return d;})

Answer Source

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 that previously existing <div>, and your "enter" selection will have one element fewer (to read more about it, see this example at S.O. Docs: The role of placeholders in "enter" selections)

Solution: remove the div with class project__bar-chart.

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download