Skip to content

Instantly share code, notes, and snippets.

@caged
Created April 13, 2012 23:30
Show Gist options
  • Save caged/2380942 to your computer and use it in GitHub Desktop.
Save caged/2380942 to your computer and use it in GitHub Desktop.
quick hack experiment
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: none;
stroke: #c00;
stroke-width: 2px;
}
path.trend {
stroke: green;
}
</style>
<body>
<script src="http://mbostock.github.com/d3/d3.v2.js?2.8.1"></script>
<script>
function leastsquares(values) {
var sumx = 0,
sumy = 0,
sumxy = 0,
sumxx = 0,
count = 0,
x = 0,
y = 0,
m = 0,
b = 0,
i = 0,
len = values.length
/*
* Calculate the sum for each of the parts necessary.
*/
values.forEach(function(v) {
x = v.x
y = v.y
sumx = x
sumy = y
sumxx += x * x
sumxy += x * y
count++
})
/*
* Calculate m and b for the formular:
* y = x * m + b
*/
m = (count * sumxy - sumx * sumy) / (count * sumxx - sumx * sumx);
b = (sumy / count) - (m * sumx) / count;
/*
* We will make the x and y result line now
*/
var result_values_x = [];
var result_values_y = [];
return values.map(function(v) {
x = v.x
y = x * m + b
return {x: x, y: y}
})
}
var data, h, max, pb, pl, pr, pt, vis, w, x, y, _ref;
data = [3, 7, 9, 12, 10, 15, 20, 18, 19, 24, 25];
_ref = [20, 20, 20, 20], pt = _ref[0], pl = _ref[1], pr = _ref[2], pb = _ref[3];
w = 800 - (pl + pr);
h = 300 - (pt + pb);
max = d3.max(data);
x = d3.scale.linear().domain([0, data.length - 1]).range([0, w]);
y = d3.scale.linear().domain([0, max]).range([h, 0]);
vals = [];
vis = d3.select(document.body)
.style('margin', '20px auto')
.style('width', "" + w + "px").append('svg:svg')
.attr('width', w + (pl + pr))
.attr('height', h + pt + pb)
.attr('class', 'viz')
.append('g')
.attr('transform', "translate(" + pl + "," + pt + ")");
data.forEach(function(d, i) {
vals.push({x: x(i), y: y(d)})
})
vis.selectAll('path.line')
.data([vals])
.enter().append("path")
.attr("d", d3.svg.line()
.x(function(d) { return d.x;})
.y(function(d) { return d.y }));
vis.selectAll('path.trend')
.data([leastsquares(vals)])
.enter().append("path")
.classed('trend', true)
.attr("d", d3.svg.line()
.x(function(d) { return d.x;})
.y(function(d) { return d.y }));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment