Skip to content

Instantly share code, notes, and snippets.

@d3byex
Created November 19, 2015 21:14
Show Gist options
  • Save d3byex/8324149269d6893f765b to your computer and use it in GitHub Desktop.
Save d3byex/8324149269d6893f765b to your computer and use it in GitHub Desktop.
D3byEX 4.2: Bars with Labels
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<meta name="description" content="D3byEX 4.2" />
<meta charset="utf-8">
</head>
<body>
<script>
var data = [55, 44, 30, 23, 17, 14, 16, 25, 41, 61, 85,
101, 95, 105, 114, 150, 180, 210, 125, 100, 71,
75, 72, 67];
var barWidth = 20, barPadding = 3;
var maxValue = d3.max(data);
var mainGroup = d3.select('body')
.append('svg')
.attr({ width: 1000, height: 250 })
.append('g');
function xloc(d, i) { return i * (barWidth + barPadding); }
function yloc(d) { return maxValue - d; }
function translator(d, i) {
return "translate(" + xloc(d, i) + "," + yloc(d) + ")";
}
var barGroups = mainGroup.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('transform', translator);
barGroups.append('rect')
.attr({
fill: 'steelblue',
width: barWidth,
height: function(d) { return d; }
});
var textTranslator = "translate(" + barWidth / 2 + ",0)";
barGroups.append('text')
.text(function(d) { return d; })
.attr({
fill: 'white',
'alignment-baseline': 'before-edge',
'text-anchor': 'middle',
transform: textTranslator
})
.style('font', '10px sans-serif');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment