Skip to content

Instantly share code, notes, and snippets.

@mukhtyar
Last active January 11, 2018 23:40
Show Gist options
  • Save mukhtyar/2eaf29426bdc09a328fd7666a01310df to your computer and use it in GitHub Desktop.
Save mukhtyar/2eaf29426bdc09a328fd7666a01310df to your computer and use it in GitHub Desktop.
D3 - Enter, Update, Exit
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; }
#chart {
margin: 3em;
}
.bar {
background-color: blue;
height: 20px;
margin-top: 2px;
}
</style>
</head>
<body>
<svg id="chart"></svg>
<script>
var rectWidth = 50;
var chartHeight = 400;
var chartWidth = 700;
//var data = [200, 60, 100, 80, 10];
var svg = d3.select('#chart')
.attr('height', chartHeight)
.attr('width', chartWidth);
function render(data){
// bars includes update selection
var bars = svg.selectAll('rect')
.data(data, d => d);
// exit
bars.exit().transition().remove();
// enter
var enter = bars.enter().append('rect')
.attr('width', rectWidth)
.attr('stroke', '#FF00FF')
.attr('stroke-width', '2');
// enter + update
bars = enter.merge(bars).transition()
.attr('x', function(d, i){
return i * rectWidth;
})
.attr('y', function(d){
return chartHeight - d;
})
.attr('height', function(d){
return d;
})
.attr('fill', 'blue');
}
setInterval(function(){
var data = [];
var dataLength = Math.floor(Math.random() * 10) + 1;
for (var i=0, t=dataLength; i<t; i++) {
data.push(Math.round(Math.random() * t * 50))
}
console.log(data);
render(data);
}, 3000);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment