Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.chart {
background-color: #f6f7f9;
margin: 15px;
padding: 10px
}
.bar {
fill: green;
height: 30px;
stroke: #f6f7f9;
stroke-width: 4;
}
.bar:hover {
fill: red;
}
.label {
fill: white;
}
</style>
</head>
<body>
<div class="chart"></div>
<script>
const scores = [
{ name: 'Alice', score: 96 },
{ name: 'Billy', score: 83 },
{ name: 'Cindy', score: 91 },
{ name: 'David', score: 96 },
{ name: 'Emily', score: 88 }
];
const margin = { top: 25, right: 15, bottom: 25, left: 15 };
const width = 425 - margin.left - margin.right;
const height = 625 - margin.top - margin.bottom;
const setOpacity = (selection, opacity) =>
selection.style('fill-opacity', opacity);
const svg = d3.select('.chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
const enter = svg.selectAll('rect')
.data(scores)
.enter();
enter.append('rect')
.attr('transform', (d, i) =>
'translate(0, ' + i * 30 + ')')
.style('width', d => d.score)
.attr('class', 'bar')
.on('click', function(d, i, elements) {
console.log(`${d.name} = ${d.score}`);
console.log('d, i, el: ', d, i, elements);
})
.on('mouseover', function(d, i, elements) {
d3.selectAll(elements)
.filter(':not(:hover)')
.call(setOpacity, 0.5)
})
.on('mouseout', function(d, i, elements) {
d3.selectAll(elements).call(setOpacity, 1);
});
enter.append('text')
.attr('y', (d, i) => i * 30 + 20)
.attr('x', 5)
.attr('class', 'label')
.text(d => d.name);
</script>
</body>
https://d3js.org/d3.v4.min.js