Skip to content

Instantly share code, notes, and snippets.

@mattwigway
Last active December 16, 2015 11:29
Show Gist options
  • Save mattwigway/5427723 to your computer and use it in GitHub Desktop.
Save mattwigway/5427723 to your computer and use it in GitHub Desktop.
Half-life visualization (distance decay for a gravity model)

Distance decay

This shows the distance decay for a given half-life in the gravity model, i.e. e^bx fixed by 0,1 and h,0.5 where h is the half-life.

function GravityDemo () {
var object = this;
this.svg = d3.select('#graph')
.append('svg')
.attr('width', 800)
.attr('height', 600)
.append('g');
this.updateValue(1);
this.xScale = d3.scale.linear().range([0, 800]).domain([0, 120]);
this.yScale = d3.scale.linear().range([600, 0]).domain([0, 1]);
// I know they're backwards, but then the labels are in the graph space
this.xAxis = d3.svg.axis().scale(this.xScale).orient('top');
this.yAxis = d3.svg.axis().scale(this.yScale).orient('right');
this.svg.append('g').attr('transform', 'translate(0, 600)').call(this.xAxis);
this.svg.append('g').call(this.yAxis);
this.line = d3.svg.line()
.x(function (d) { return object.xScale(d[0]) })
.y(function (d) { return object.yScale(d[1]) });
this.path = this.svg.append('g').append('path')
.datum(this.data)
.attr('d', this.line);
}
GravityDemo.prototype.updateValue = function (value) {
this.data = [];
var beta = Math.log(.5) / value;
for (var i = 0; i <= 120; i++) {
this.data.push([i, Math.pow(Math.E, beta * i)])
}
};
GravityDemo.prototype.redraw = function () {
this.path.datum(this.data).transition().attr('d', this.line);
};
g = new GravityDemo();
d3.select('#halfLife').on('change', function () {
g.updateValue(this.value);
g.redraw();
d3.select('#currentHalfLife').text(this.value);
});
<!DOCTYPE html>
<html>
<head>
<title>Graph of accessibility measures</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
svg { fill: none; stroke: steelblue; stroke-width: 1px }
</style>
</head>
<body>
<div id="graph" style="width: 800px; height: 600px;"></div>
<label for="halfLife">Half-life (minutes)</label>: <input type="range" id="halfLife" min="1" max="90" value="5" /><span id="currentHalfLife"></span>
<script src="gravityDemo.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment