D3 spacing between bars

10,020

Solution 1

Give a margin-top like this:

d3.select("#chart")
  .selectAll("div")
    .data(data)
  .enter().append("div")
    .style("width", function(d) { return x(d) + "px"; })
    .style("background-color", "red")
    .style("margin-top", "10px") //give margin-top for spacing between bars
    .text(function(d) { return d; });

working code here

Solution 2

Those bars exist inside DOM as divs, which means that you can use traditional styling of divs to add spacing.

Find this section:

.chart div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}

and change margin: 1px; to whatever you want the spacing to be.

You should be careful though, because usually d3 doesn't operate on divs, but on SVG or canvas elements. For that, the method for changing bar spacing would be different.

Share:
10,020
user3837019
Author by

user3837019

Updated on August 21, 2022

Comments

  • user3837019
    user3837019 over 1 year

    I'm new to D3 and was hoping if someone could help me with trying to figure out how I can add some spacing between the individual bars. Here's the code:

    var data = [4, 8, 15, 16, 23, 42];
    
    var x = d3.scale.linear()
        .domain([0, d3.max(data)])
        .range([0, 420]);
    
    d3.select(".chart")
      .selectAll("div")
        .data(data)
      .enter().append("div")
        .style("width", function(d) { return x(d) + "px"; })
        .text(function(d) { return d; });
    

    I'm following this example to create the bar chart https://bost.ocks.org/mike/bar/

  • user3837019
    user3837019 about 8 years
    Thank you for the explanation and answer. Seems to work well.
  • user3837019
    user3837019 about 8 years
    Didn't actually consider using margin-top in a .style. Thanks for the help.