Skip to content

Instantly share code, notes, and snippets.

Created February 21, 2018 04:14
fresh block
license: mit
<!DOCTYPE html>
<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; }
#container { height: 800px; width: 800px; margin: 40px auto; border: 1px solid;}
.bar { height: 20px; background-color: moccasin; margin: 5px; }
</style>
</head>
<body>
<div id='container'>
<button onclick="render('math')">Math</button>
<button onclick="render('science')">Science</button>
</div>
<script>
// Feel free to change or delete any of the code you see in this editor!
const data = [
{ name: 'Alice', math: 93, science: 84 },
{ name: 'Bobby', math: 81, science: 97 },
{ name: 'Carol', math: 74, science: 88 },
{ name: 'David', math: 64, science: 76 },
{ name: 'Emily', math: 80, science: 94 }
];
const width = 400;
const height = 600;
const xScale = d3.scaleLinear()
.domain([0, 100])
.range([1, width])
function render(subject) {
const bars = d3.select('#container')
.selectAll('div')
.data(data, function(d) {
return d.name
});
const newBars = bars.enter()
.append('div')
.attr('class', 'bar')
.style('width', 0)
newBars.merge(bars)
.transition()
.style('width', function(d) {
return xScale(d[subject] + 'px')})
}
render('math');
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment