Skip to content

Instantly share code, notes, and snippets.

@topicus
Created August 12, 2015 13:45
Show Gist options
  • Save topicus/217444acb4204f364e46 to your computer and use it in GitHub Desktop.
Save topicus/217444acb4204f364e46 to your computer and use it in GitHub Desktop.
Add labels to MultiBarCharts in NVD3
// You need to apply this once all the animations are already finished. Otherwise labels will be placed wrongly.
d3.selectAll('.nv-multibar .nv-group').each(function(group){
var g = d3.select(this);
// Remove previous labels if there is any
g.selectAll('text').remove();
g.selectAll('.nv-bar').each(function(bar){
var b = d3.select(this);
var barWidth = b.attr('width');
var barHeight = b.attr('height');
g.append('text')
// Transforms shift the origin point then the x and y of the bar
// is altered by this transform. In order to align the labels
// we need to apply this transform to those.
.attr('transform', b.attr('transform'))
.text(function(){
// Two decimals format
return parseFloat(bar.y).toFixed(2);
})
.attr('y', function(){
// Center label vertically
var height = this.getBBox().height;
return parseFloat(b.attr('y')) - 10; // 10 is the label's magin from the bar
})
.attr('x', function(){
// Center label horizontally
var width = this.getBBox().width;
return parseFloat(b.attr('x')) + (parseFloat(barWidth) / 2) - (width / 2);
})
.attr('class', 'bar-values');
});
});
@traviskds27
Copy link

How to detect when all the animations are already finished. Trying to see if I can capture that event but haven't been able to figure it out as yet.

@traviskds27
Copy link

I added a $timeout delay to then display the values. So its all good.

@Ivutar
Copy link

Ivutar commented Apr 12, 2016

How to detect when all the animations are already finished.

chart.dispatch.on('renderEnd', function() { ... });

@prateek-verma
Copy link

Hi,

I need to do the same for "multibarHorizontal"

did below changes

d3.selectAll('.nv-multibarHorizontal

but

b.attr('width');
var barHeight = b.attr('height');

are null.

Thanks!

@obdulia-losantos
Copy link

Try with b.node().getBBox(), you'll get all the dimension you need { x: #, y: #, width: #, height: # }

@willglanville
Copy link

Very useful thanks.

Is it possible to make labels a different colour from the bars?

@DavidDenk27
Copy link

Yeah it is possible.

Try only add the style attribute.

.attr('class', 'bar-values')
.style("stroke","black");

@patrick-melo
Copy link

This is wonderful, thank you.

Is there any way to rotate the labels 90% so that they work their way up the graph?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment