Skip to content

Instantly share code, notes, and snippets.

@nkabrown
Created November 11, 2015 01:53
Show Gist options
  • Save nkabrown/33678dd2c8db41d80bc5 to your computer and use it in GitHub Desktop.
Save nkabrown/33678dd2c8db41d80bc5 to your computer and use it in GitHub Desktop.
create or convert a chart to display elements with percentages in d3.js
// percentage = value / total * 100
// store total in variable
var total = d3.sum(data, function(d) { return d.values; });
// set upper domain of y-axis not to 100% but to the percentage of the greatest value in your data
y.domain([0, d3.max(data, function(d) { return Math.round((d.values / total) * 100); })]);
// percentage in bar chart
var bars = d3.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('width', x.rangeBand())
.attr('x', function(d) { return x(d.key); })
.attr('y', function(d) { return y(Math.round((d.values / total) * 100)); })
.attr('height', function(d) { return height - y(Math.round((d.values / total) * 100)); })
.style('fill', color(colorKey));
// percentage in a tooltip
tooltip.html('Percent: ' + Math.round((d.values / total) * 100) + '%');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment