最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - D3 spacing between bars - Stack Overflow

programmeradmin0浏览0评论

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 /

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/mike/bar/

Share Improve this question asked Apr 14, 2016 at 6:53 user3837019user3837019 2211 gold badge3 silver badges18 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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

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.

width = 100; Try to add .attr("width", width/data.length - 10) Or if you make as in example you need to add "height" attribute to make vertical spaces

发布评论

评论列表(0)

  1. 暂无评论