Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created June 18, 2012 15:04
Show Gist options
  • Save benshimmin/2948804 to your computer and use it in GitHub Desktop.
Save benshimmin/2948804 to your computer and use it in GitHub Desktop.
Plotting a line of best fit using linear regression in CoffeeScript with Raphael JS
$ ->
new ScatterGraph "scattergraph"
class ScatterGraph
constructor : (target) ->
@paper = Raphael target
bg = @paper.rect 0, 0, 500, 500
bg.attr
stroke : "none"
fill : "#f0f0f0"
@points = []
@drawAxes()
$(bg.node).on "click", (event) =>
@points.push(new Point(event.offsetX, event.offsetY).plot @paper)
@len = @points.length
@plotLinearRegression()
drawAxes : ->
@paper.path "M0,0L0,500"
@paper.path "M0,500L500,500"
plotLinearRegression : =>
return unless @len > 1
sumX = 0
sumY = 0
sumXY = 0
sumX2 = 0
sumX += point.x for point in @points
sumY += point.y for point in @points
sumXY += point.x * point.y for point in @points
sumX2 += point.x * point.x for point in @points
div = (@len * sumX2) - (sumX * sumX)
intercept = ((sumY * sumX2) - (sumX * sumXY)) / div
slope = ((@len * sumXY) - (sumX * sumY)) / div
getPoint = (x) ->
"#{x}," + (intercept + (x * slope))
@bestFit.remove() if @bestFit
@bestFit = @paper.path "M#{getPoint 0}L#{getPoint 500}"
class Point
constructor : (x, y) ->
@x = x
@y = y
plot : (paper) ->
paper.circle @x, @y, 5
@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment