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

空扰寡人 提交于 2019-12-07 10:17:19

问题


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.


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/27499347/how-to-add-space-between-bars-in-a-grouped-bar-chart-in-a-nvd3-grouped-multibar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!