Skip to content

Instantly share code, notes, and snippets.

@biovisualize
Created March 6, 2016 05:40
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 biovisualize/1c0c7ad51d3d28481cea to your computer and use it in GitHub Desktop.
Save biovisualize/1c0c7ad51d3d28481cea to your computer and use it in GitHub Desktop.
1-D Random Walk

Foundations of D3: Manual Scaling

A 1-dimensional random walk visualized. To better understand what scales are doing, avoids using D3's build in scales and instead manually computes a step size as well as a starting position from which to walk.

  1. You should use blockbuilder.org and the following Javascript and d3 functions to adjust the num_steps and radius to see how the path changes
  2. Once you have a feel for the parameters, make a line chart instead. For extra credit gradient encode the random walk path.

Reference

forked from Jay-Oh-eN's block: 1-D Random Walk

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
path {
fill: none;
stroke: black
}
circle {
fill: red;
}
</style>
</head>
<body>
<script>
var width = 960;
var height = 500;
var numSteps = 250;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var position = height / 2;
var stepSize = width / numSteps;
var step = 0;
var walkStepSize = 10;
var path = [];
var line = d3.svg.line()
.x(function(d){ return d.x; })
.y(function(d){ return d.y; });
var rnd = d3.random.normal(0, 1);
for (var i = 0; i < numSteps; i++) {
position += rnd() * walkStepSize;
step += stepSize;
path.push({x: step, y: position});
svg.append('circle')
.attr('cx', step)
.attr('cy', position)
.attr('r', 2);
}
svg.append('path')
.attr({d: line(path)})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment