Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
</head>
<body>
<svg class="chart" />
<script>
var data = [42, 99, 30, 17, 14];
var width = 650,
barHeight = 50;
var colorScale = d3.scaleOrdinal(d3.schemeCategory10);
var x = d3.scaleLinear()
.domain([0, d3.sum(data)])
.range([0, width]);
function xScaleAccumulator(data) {
let accumXScale = [0];
let tracker = 0;
for (let i = 0; i < data.length; i++) {
tracker += x(data[i]);
accumXScale.push(tracker);
}
return accumXScale;
}
var accumXScale = xScaleAccumulator(data);
function getLabelPositions(data) {
let positions = [];
let tracker = 0;
for (let i = 0; i < data.length; i++) {
positions.push((accumXScale[i + 1] - accumXScale[i]) / 2);
}
return positions
}
var labelPositions = getLabelPositions(data);
console.log('accumX ' + accumXScale)
console.log('labelPos ' + labelPositions)
var chart = d3.select('.chart')
.attr('width', width)
.attr('height', barHeight * data.length);
var bar = chart.selectAll('g')
.data(data)
.enter().append('g')
.attr('transform', function(d, i) { return "translate("+ accumXScale[i] +")"; });
bar.append('rect')
.attr('width', x)
.attr('height', barHeight - 1)
.style('fill', function(d, i) { return colorScale(i); });
bar.append('text')
.attr('transform', function(d, i) { return "translate("+ labelPositions[i] +")"; })
.attr('y', barHeight / 2)
.attr('dy', '.35em')
.text(function(d) { return d; });
</script>
</body>
https://d3js.org/d3.v4.min.js