Skip to content

Instantly share code, notes, and snippets.

@TommyCoin80
Last active February 1, 2017 21:20
Show Gist options
  • Save TommyCoin80/14addf8a1754fdc3c775a8d0626cc9c5 to your computer and use it in GitHub Desktop.
Save TommyCoin80/14addf8a1754fdc3c775a8d0626cc9c5 to your computer and use it in GitHub Desktop.
Ten Random Walk Bars
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<style>
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<body>
<script>
var margin = {top: 30, right: 30, bottom: 50, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body")
.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 + ")");
var data = d3.range(0,10,1).map(function(d) {
return d3.randomUniform(0,100)();
})
var x = d3.scaleBand()
.domain(data.map(function(d,i) { return i;}))
.range([0,width])
.padding(.1);
var y = d3.scaleLinear()
.domain([d3.min(data.map(function(d) { return d}))-10,d3.max(data.map(function(d) { return d}))+10])
.range([height,0]);
var color = d3.scaleOrdinal(d3.schemeCategory10)
.domain(x.domain());
var xAxis = d3.axisBottom(x);
var yAxis = d3.axisLeft(y);
svg.append("g")
.attr("class","axis x")
.attr("transform","translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class","axis y")
.call(yAxis);
var duration = 250,
ease = d3.easeLinear;
var bars = svg.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("x", function(d,i) { return x(i)})
.attr("y", function(d) { return y(d);})
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d);})
.style("fill", function(d) { return color(d)})
bars.transition()
.duration(duration)
.ease(ease)
.on("start", tick);
function tick(d,i) {
data[i] = data[i] + d3.randomUniform(-20,20)();
y.domain([d3.min(data.map(function(d) { return d}))-10,d3.max(data.map(function(d) { return d}))+10])
if(i==data.length-1) {
svg.select(".axis.y").transition()
.duration(duration)
.ease(ease)
.call(yAxis);
}
d3.active(this).attr("y", y(data[i]))
.attr("height", height - y(data[i]))
.on("end", function() {
if(i==data.length-1) {
bars.transition()
.duration(duration)
.ease(ease)
.on("start", tick);
}
})
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment