Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active November 22, 2018 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romsson/45cd4abcc604ea4fe96cc9574047c94a to your computer and use it in GitHub Desktop.
Save romsson/45cd4abcc604ea4fe96cc9574047c94a to your computer and use it in GitHub Desktop.
bar chart data binding
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; }
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg")
.attr("width", 800)
.attr("height", 600)
.attr("transform", "translate(10, 300)")
var max = 100, n = 100;
var data = [];
function generate_data(n) {
data = d3.range(n).map(function(d) { return Math.random() * max}) ;
}
generate_data(n);
var x = d3.scaleBand()
.domain(d3.range(n))
.range([0, 400])
var y = d3.scaleLinear()
.domain([0 , d3.max(data)])
.range([0, 100])
function draw() {
// CREATION
svg.selectAll("rect").data(data)
.enter()
.append("rect")
.attr("x", function(d, i) { return x(i); })
.attr("y", function(d, i) { return 100 - y(d); })
.attr("height", function(d, i) { return y(d); })
.attr("width", x.bandwidth() - 1)
.style("fill", "green");
// UPDATE
svg.selectAll("rect").data(data)
.transition().delay(function(d, i) { return i * 10; })
.attr("x", function(d, i) { return x(i); })
.attr("y", function(d, i) { return 100 - y(d); })
.attr("height", function(d, i) { return y(d); })
.attr("width", x.bandwidth() - 1)
.style("fill", "blue")
// SUPPRESSION
svg.selectAll("rect").data(data)
.exit()
.style("fill", "red")
// .transition(100)
.remove()
}
draw()
setInterval(function() {
n = Math.floor(Math.random() * 200);
// x.domain(d3.range(n))
generate_data(n);
draw()
}, 1000)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment