简体   繁体   中英

How to add space between bars in a grouped bar chart in a nvd3 grouped multibar chart?

I'm trying to add some space/padding for a nvd3 multi bar chart. "groupSpacing" is not what I need, since it only adds space between groups. I'll need space between each bar inside group. I found one link in github support . Can you post any solution or tweak?

I also found a d3 example of grouped bar chart . Any help in this example also very helpful to me.

Thanks.

I have draw a d3 group barchart:

fiddle

You can adjust the groupSpacing by change the code on line 56:

var groupSpacing = 6;

Technically i just achieve it by change the width of each rects' width:

var barsEnter = bars.enter().append('rect')
                .attr('class', 'stm-d3-bar')
                .attr('x', function(d,i,j) {
                    return (j * x1.rangeBand() );
                })
                .attr('y', function(d) { return y(d.y); })
                .attr('height', function(d) { return height - y(d.y); })
                .attr('width', x0.rangeBand() / barData.length - groupSpacing )
                .attr('transform', function(d,i) { 
                  return 'translate(' + x0(d.x) + ',0)'; 
                })
                .style("fill", function(d, i, j) { 
                  return color(data[j].key); 
                });

Hope it helps you understand how you can achieve it in d3.

I minus the number of group spacing from the "width" attribute also. I found that the x-axis label looks a little off after I did that so I add the (group spacing / 2) to the "x" attribute. Here is the example of my code.

var groupSpacing = 15;
var rect = groups.selectAll("rect")
  .data(function (d) { return d; })
  .enter()
  .append("rect")
  .attr("x", function (d) { return x(d.x) + (groupSpacing / 2) ; })
  .attr("y", function (d) { return y(d.y0 + d.y); })
  .attr("height", function (d) { return y(d.y0) - y(d.y0 + d.y); })
  .attr("width", x.rangeBand() - groupSpacing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM