Created
November 11, 2015 01:53
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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