Last active
September 3, 2015 19:54
-
-
Save ivanpepelko/dbd798527769364a6403 to your computer and use it in GitHub Desktop.
Dotabuff trendline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
var svg = $('.player-chart-container svg'); //selector is valid only for charts under Trends pages | |
if (typeof (svg[0]) !== 'undefined') { //if there is no graph in page, do nothing | |
$('#trendline').remove(); //remove previously drawn line | |
var points = $('circle'); //get all graph points | |
//calculate parameters needed for trendline | |
var cnt = points.length; | |
var sumx, sumy, sumx2, sumxy; | |
sumx = sumy = sumx2 = sumxy = 0; | |
points.each(function () { | |
var c, x, y; | |
c = $(this); | |
x = parseFloat(c.attr('cx')); | |
y = parseFloat(c.attr('cy')) | |
sumx += x; | |
sumy += y; | |
sumx2 += Math.pow(x, 2); | |
sumxy += x * y; | |
}); | |
//line function: "y = k * x + l", also known as "y = m * x + b" or "y = alpha * x + beta" | |
var k = ((cnt * sumxy) - (sumx * sumy)) / ((cnt * sumx2) - Math.pow(sumx, 2)); | |
var l = (sumy - k * sumx) / cnt; | |
//line points | |
var x1 = points.eq(0).attr('cx'); | |
var x2 = points.last().attr('cx'); | |
var y1 = k * x1 + l; | |
var y2 = k * x2 + l; | |
var lineString = x1 + ',' + y1 + ',' + x2 + ',' + y2; | |
var color = 'FBB829'; //yellow | |
if (y1 > y2) | |
color = 'A9CF54'; //green | |
else | |
color = 'C23C2A'; //red | |
var line = '<g class=line id=trendline><path stroke="#' + color + '" stroke-width="2" fill="none" d="M' + lineString + '"></g>'; | |
//all g elements inside svg element contain transform attr | |
//eq(0) will select the topmost one | |
svg.find('g[transform]').eq(0).append(line); | |
//Remove closing tag, it must be done from any parent element. | |
//If closing tag is not removed, the line will not be displayed. | |
svg[0].innerHTML = svg[0].innerHTML.replace('</path>', ''); | |
} | |
}) (); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment