Making the width of the bars dynamic

Currently, our bars have a fixed width. No matter how many elements we have, they have a 15 px width. If we had more data elements, the bars could overlap. Let's change this. Since each rect will be the same width, no matter what the data is, we can just assign width a computed value. Add the following to the end of the AJAX callback:

d3.selectAll('rect')
    .attr('width', WIDTH/data.length);

Now let's adjust our rect CSS so our bars are more visible:

rect {
    /*  remove the width rule that was here */
    stroke:white;
    stroke-width:1px;
}

The output will be shown as follows:

Get D3.js Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.