-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.js
655 lines (585 loc) · 17.8 KB
/
graph.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/*
* graph.js
* A tool for plotting points using Javascript and the HTML5 Canvas element.
* Created by John Mauney for http://plotpoints.net
*/
var title = "My Cool Graph";
var xLabel = "X Axis Label";
var yLabel = "Y Axis Label";
var canvasWidth = 500;
var canvasHeight = 500;
var axesOffset = 50;
var graphWidth = canvasWidth - (2 * axesOffset);
var graphHeight = canvasHeight - (2 * axesOffset);
var xMax = 15;
var xMin = 0;
var yMax = 15;
var yMin = 0;
var msg = "";
var numAxisMarkers = 15;
var pointSize = 4;
var alpha = 0.2;
var showBorder = true;
var showCoords = true;
var showGrid = true;
var showLines = true;
var showPoints = true;
var linearClicked = false;
var linearColor = document.getElementById("linearColor").value;
var polyColor = document.getElementById("polynomialColor").value;
var polynomialClicked = false;
var polynomialOrder = 3;
var coords = new Array();
var c = document.getElementById("myCanvas");
var canvOK = 1;
var fromURL = false;
//check if a graph is in the url and assign its values if so
parseLink();
//load a random example scenario if no url data
if (!fromURL) {
loadScenario();
}
//draw the canvas
paintCanvas();
//draws everything to canvas
function paintCanvas() {
try {c.getContext("2d");}
catch (er) {canvOK=0;}
if (canvOK==1) {
//begin by clearing canvas
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
//set canvas attributes
c.setAttribute("width", canvasWidth);
c.setAttribute("height", canvasHeight);
//create blank canvas
var ctx=c.getContext("2d");
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
//draw each point
replot();
//draw graph elements
drawBorder();
drawAxes();
drawLabels();
drawLines();
linearClicked = false;
polynomialClicked = false;
}
}
//load a random scenario from a predefined group
function loadScenario() {
//load a set of points and define axes
var scenario = parseInt(Math.random()*2);
switch (scenario) {
case 0:
xMax = 15;
yMax = 15;
numAxisMarkers = 15
addPoint(1, 9);
addPoint(3, 2);
addPoint(5, 6);
addPoint(6, 1);
addPoint(9, 4);
addPoint(12, 8);
break;
case 1:
xMax = 400;
yMax = 400;
numAxisMarkers = 8;
addPoint(300, 175);
addPoint(375, 250);
addPoint(100, 25);
addPoint(209, 75);
addPoint(0, 0);
addPoint(200, 100);
addPoint(50, 150);
addPoint(123, 69);
addPoint(340, 222);
break;
}
//randomly generated version, may work on this later
// xMax = parseInt(Math.random()*9 + 1)*100;
// yMax = parseInt(Math.random()*9 + 1)*100;
// numAxisMarkers = 10;
// var pointQuantity = 3 + parseInt(Math.random()*9);
// for(var i = 0; i < pointQuantity; i++) {
// addPoint(parseInt(Math.random()*1000) % xMax, parseInt(Math.random()*1000) % yMax);
// }
}
//comparator for sorting coordinates
function compare(a, b) {
return a[0] - b[0];
}
//draw the x and y axes
function drawAxes() {
//draw axes
var ctx = c.getContext("2d");
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(axesOffset, axesOffset);
ctx.lineTo(axesOffset, canvasHeight - axesOffset);
ctx.lineTo(canvasWidth - axesOffset, canvasHeight - axesOffset);
ctx.strokeStyle = "#000000";
ctx.stroke();
//draw interval markers
var markLength = 5;
xInterval = xMax / numAxisMarkers;
yInterval = yMax / numAxisMarkers;
ctx.font = "12px Courier";
ctx.fillStyle = "#000000";
//x axis interval markers
for (var i = 1; i < numAxisMarkers + 1; i++) {
ctx.beginPath();
ctx.moveTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset);
ctx.lineTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset - markLength); //5 = marker length
ctx.stroke();
ctx.textAlign = "center";
ctx.fillText(Number((i * xInterval).toFixed(3)), axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset + 12); //12 is text offset
//draw the grid if enabled
if (showGrid) {
ctx.save();
ctx.globalAlpha = alpha;
ctx.moveTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset);
ctx.lineTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset - graphWidth);
ctx.stroke();
ctx.restore();
}
}
//y axis interval markers
for (var i = 1; i < numAxisMarkers + 1; i++) {
ctx.beginPath();
ctx.moveTo(axesOffset, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));
ctx.lineTo(axesOffset + markLength, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers))); //5 = marker length
ctx.stroke();
ctx.textAlign = "right";
ctx.fillText(Number((i * yInterval).toFixed(3)), axesOffset - 4, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)) + 3); //4 and 3 are text offset
//draw the grid if enabled
if (showGrid) {
ctx.save();
ctx.globalAlpha = alpha;
ctx.moveTo(axesOffset, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));
ctx.lineTo(axesOffset + graphHeight, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));
ctx.stroke();
ctx.restore();
}
}
//draw "0" at origin
ctx.fillText("0", axesOffset - 4, canvasHeight - axesOffset + 4);
}
//draw a border
function drawBorder() {
if (showBorder) {
//simply draw a line around the edge of the canvas
var ctx = c.getContext("2d");
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(canvasWidth, 0);
ctx.lineTo(canvasWidth, canvasHeight);
ctx.lineTo(0, canvasHeight);
ctx.lineTo(0, 1);
ctx.stroke();
}
}
//draw the title and the axis labels
function drawLabels() {
var ctx = c.getContext("2d");
ctx.font = "12px Courier";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.fillText(title, canvasWidth / 2, 25); //title
ctx.fillText(xLabel, canvasWidth / 2, canvasHeight - 15); //x-axis label
//the canvas must be rotated to draw vertical text
ctx.save(); //save canvas position so it can be restored
ctx.font = "14px Courier";
ctx.translate(15, canvasHeight / 2); //move canvas in position
ctx.rotate(Math.PI * 1.5); //rotate canvas
ctx.fillText(yLabel, 0, 0);
ctx.restore(); //restore canvas
}
//draw a line given slope and initial y value
function drawLinearFunc(slope, y0) {
//ratios for line to move as axes change
var xRatio = graphWidth / xMax;
var yRatio = graphHeight / yMax;
var ctx = c.getContext("2d");
ctx.lineWidth = 2;
if (fromURL) {
ctx.strokeStyle = linearColor;
} else {
ctx.strokeStyle = document.getElementById("linearColor").value;
}
ctx.beginPath();
//calculate beginning point
if (slope >= 0) {
var xIntercept = 0;
if (y0 >= 0) {
ctx.moveTo(axesOffset, canvasHeight - axesOffset - (y0 * yRatio));
} else {
ctx.moveTo(axesOffset - yRatio * (y0 / slope), canvasHeight - axesOffset);
}
} else {
if (y0 >= yMax) {
ctx.moveTo(axesOffset + yRatio * ((yMax - y0) / slope), axesOffset);
} else {
ctx.moveTo(axesOffset, canvasHeight - axesOffset - (y0 * yRatio));
}
}
//calculate end point
if (slope >= 0){
var x1 = (yMax - y0) / slope;
var y1 = (xMax * slope) + y0;
if (x1 <= xMax){
ctx.lineTo(axesOffset + (x1 * xRatio), axesOffset);
} else {
ctx.lineTo(canvasWidth - axesOffset, canvasHeight - axesOffset - (y1 * yRatio));
}
} else {
var x1 = -y0 / slope;
var y1 = (xMax * slope) + y0;
if (x1 <= xMax){
ctx.lineTo(axesOffset + (x1 * xRatio), canvasHeight - axesOffset);
} else {
ctx.lineTo(canvasWidth - axesOffset, canvasHeight - axesOffset - (y1 * yRatio));
}
}
ctx.stroke();
//print function to textarea
msg += "f(x) = " + slope + "x + " + y0 + "\n\n";
printMSG(msg);
}
//draw a polynomial given an array of coefficients
function drawPolynomial(X) {
var xRatio = graphWidth / xMax;
var yRatio = graphHeight / yMax;
var n = X.length;
var precision = 10000;
var fX = 0;
var ctx = c.getContext("2d");
var strokeOn = true;
ctx.lineWidth = 1;
if (fromURL) {
ctx.strokeStyle = polyColor;
} else {
ctx.strokeStyle = document.getElementById("polynomialColor").value;
}
ctx.beginPath(axesOffset, canvasHeight - axesOffset - (X[n-1] * yRatio));
for (var i = 0; i <= precision; i++) {
xVar = (i * (graphWidth / precision) / (xRatio));
fX = 0;
for (var j = 0; j < n; j++) {
fX += X[j] * Math.pow(xVar, (n - 1) - j);
}
//skip drawing if yMax < f(x) < 0
if ((fX > yMax) || (fX < yMin)) {
if (strokeOn) {
ctx.stroke();
strokeOn = false;
} else {
ctx.moveTo(axesOffset + (i * (graphWidth / precision)), canvasHeight - axesOffset - (yRatio * fX));
}
} else {
strokeOn = true;
ctx.lineTo(axesOffset + (i * (graphWidth / precision)), canvasHeight - axesOffset - (yRatio * fX));
}
}
ctx.stroke();
//print function to textarea
msg += "f(x) = ";
for (var i = 0; i < polynomialOrder - 1; i++) {
msg += X[i].toPrecision(6) + "x^" + (X.length - i - 1) + " + ";
}
msg += X[X.length - 2].toPrecision(6) + "x + " + X[X.length - 1].toPrecision(6) + "\n\n";
printMSG(msg);
}
//draw a line connecting each plotted point
function drawLines() {
if (showLines) {
//ratios for line to move as axes change
var xRatio = graphWidth / xMax;
var yRatio = graphHeight / yMax;
var ctx = c.getContext("2d");
ctx.strokeStyle = "000000";
ctx.beginPath();
ctx.moveTo(axesOffset + (xRatio * coords[0][0]), canvasHeight - axesOffset - (yRatio * coords[0][1]));
for (var i = 1; i < coords.length; i++){
ctx.lineTo(axesOffset + (xRatio * coords[i][0]), canvasHeight - axesOffset - (yRatio * coords[i][1]));
}
ctx.stroke();
}
}
//perform a simple linear regression on the current points
function linearRegression() {
if(!linearClicked){
var slope;
var y0;
var n = coords.length;
//intialize sum variables
var x = 0;
var y = 0;
var xy = 0;
var xSquared = 0;
var ySquared = 0;
//calculate sums
for (var i = 0; i < n; i++){
x += coords [i][0];
y += coords [i][1];
xy += coords[i][0] * coords[i][1];
xSquared += coords[i][0] * coords[i][0];
ySquared += coords[i][1] * coords[i][i];
}
//calculate slope
slope = ((n * xy) - (x * y)) / ((n * xSquared) - (x * x));
//calculate y0
y0 = ((y * xSquared) - (x * xy)) / ((n * xSquared) - (x * x));
//draw the function
drawLinearFunc(slope, y0);
linearClicked = true;
} else {
paintCanvas();
}
}
//perform a polynomial regression on the current points
function polynomialRegression() {
//solve the linear system [A]t [A] [X] = [A]t [B]
polynomialOrder = parseInt(document.getElementById("polyOrder").value);
if (!polynomialClicked && polynomialOrder < coords.length) {
var precision = polynomialOrder + 1;
var n = coords.length;
var A = new Array(n); //2D
var B = new Array(n); //1D
var AtA = new Array(precision); //A transpose A
var AtB = new Array(precision); //A transpose B
//initialize and create A
for (var i = 0; i < n; i++) {
A[i] = new Array(precision);
for (var j = 0; j < precision; j++) {
A[i][j] = Math.pow(coords[i][0], precision - j - 1);
}
}
//create B
for (var i = 0; i < n; i++) {
B[i] = coords[i][1];
}
//initialize and zero AtA
for (var i = 0; i < precision; i++) {
AtA[i] = new Array(precision);
for (var j = 0; j < precision; j++) {
AtA[i][j] = 0;
}
}
//create A transpose A
for (var i = 0; i < precision; i++) {
for (var j = 0; j < precision; j++) {
for (var k = 0; k < n; k++) {
AtA[i][j] += A[k][i] * A[k][j];
}
}
}
//initialize and zero AtB
for(var i = 0; i < n; i++) {
AtB[i] = 0;
}
//create AtB
for (var i = 0; i < precision; i++) {
for (var j = 0; j < n; j++) {
AtB[i] += A[j][i] * B[j];
}
}
//gaussian elimination. adapted from rosettacode.org
var max, temp, i, j, col;
n = AtA.length; //reassign n to length of AtA
var X = new Array(n);
for (col = 0; col < n; col++) {
j = col;
max = AtA[j][j];
for (i = col + 1; i < n; i++) {
temp = Math.abs(AtA[i][col]);
if (temp > max){
j = i;
max = temp;
}
}
AtA = swapRow2D(AtA, col, j);
AtB = swapRow1D(AtB, col, j);
for (i = col + 1; i < n; i++) {
temp = AtA[i][col] / AtA[col][col];
for (j = col + 1; j < n; j++) {
AtA[i][j] -= temp * AtA[col][j];
}
AtA[i][col] = 0;
AtB[i] -= temp * AtB[col];
}
}
for (col = n - 1; col >= 0; col--) {
temp = AtB[col];
for (j = n - 1; j > col; j--) {
temp -= X[j] * AtA[col][j];
}
X[col] = temp / AtA[col][col];
}
drawPolynomial(X);
polynomialClicked = true;
} else {
paintCanvas();
//use different string for error so msg can be restored
if (polynomialOrder >= coords.length) {
var tempMsg = msg;
tempMsg += "Error: n must be less than # points\n\n";
printMSG(tempMsg);
}
}
}
//swap rows of a 1D array
function swapRow1D(A, row1, row2) {
var temp = A[row1];
A[row1] = A[row2];
A[row2] = temp;
return A;
}
//swap rows of an n*n 2D array
function swapRow2D(A, row1, row2) {
tempArray = new Array(A.length);
for (var i = 0; i < A.length; i++) {
tempArray[i] = A[row1][i];
A[row1][i] = A[row2][i];
A[row2][i] = tempArray[i];
}
return A;
}
//create a permalink to the current graph
function createLink() {
var newURL = location.href + "?title=" + title + "&xLabel=" + xLabel + "&yLabel=" + yLabel + "&xMax=" + xMax + "&yMax=" + yMax + "&numMarks=" + numAxisMarkers + "&showPoly=" + polynomialClicked + "&polyOrder=" + polynomialOrder + "&polyColor=" + document.getElementById("polynomialColor").value + "&showLinear=" + document.getElementById("linearColor").value + "&linColor=" + linearColor + "&coords=";
for (var i = 0; i < coords.length - 1; i++) {
newURL += coords[i][0] + "," + coords[i][1] + "|";
}
newURL += coords[coords.length - 1][0] + "," + coords[coords.length - 1][1];
prompt("Permalink to this graph:", newURL);
}
//parse permalink info
function parseLink() {
//first check for ? in URL
var currentURL = location.href;
var delimIndex = currentURL.indexOf("?");
if (delimIndex != -1) {
fromURL = true;
}
if (fromURL) {
//get everything after ?
var urlString = currentURL.slice(delimIndex + 1);
//split items into an array
var urlItems = urlString.split("&");
title = decodeURI(urlItems[0].slice(urlItems[0].indexOf("=") + 1));
xLabel = decodeURI(urlItems[1].slice(urlItems[1].indexOf("=") + 1));
yLabel = decodeURI(urlItems[2].slice(urlItems[2].indexOf("=") + 1));
xMax = parseInt(urlItems[3].slice(urlItems[3].indexOf("=") + 1));
yMax = parseInt(urlItems[4].slice(urlItems[4].indexOf("=") + 1));
numAxisMarkers = parseInt(urlItems[5].slice(urlItems[5].indexOf("=") + 1));
polynomialClicked = (urlItems[6].slice(urlItems[6].indexOf("=") + 1) === "true");
polynomialOrder = parseInt(urlItems[7].slice(urlItems[7].indexOf("=") + 1));
polyColor = urlItems[8].slice(urlItems[8].indexOf("=") + 1);
linearClicked = (urlItems[9].slice(urlItems[9].indexOf("=") + 1) === "true");
linearColor = urlItems[10].slice(urlItems[10].indexOf("=") + 1);
var coordString = urlItems[11].slice(urlItems[11].indexOf("=") + 1);
//split coordinate string to individual coordinates
var exitLoop = false;
var tempX = 0;
var tempY = 0;
while (!exitLoop) {
tempX = parseInt(coordString.slice(0, coordString.indexOf(",")));
coordString = coordString.slice(coordString.indexOf(",") + 1);
if (coordString.indexOf("|") == -1) {
tempY = parseInt(coordString);
exitLoop = true;
} else {
tempY = parseInt(coordString.slice(0, coordString.indexOf("|")));
coordString = coordString.slice(coordString.indexOf("|") + 1);
}
coords.push([tempX, tempY]);
}
paintCanvas();
}
}
//export the canvas to a png image
function exportToPNG() {
var img = c.toDataURL("image/png");
window.open(img);
}
//save a point's location in the coords[][] array
function addPoint(x, y) {
coords.push([x, y]);
paintCanvas();
}
//plot point from form input
function addPointFromInput() {
var x = parseFloat(document.getElementById("xCoord").value);
var y = parseFloat(document.getElementById("yCoord").value);
addPoint(x, y);
}
//redraw all points
function replot() {
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000";
ctx.font = "12px Courier";
ctx.textAlign = "left";
//sort coordinates by ascending x values
coords.sort(compare);
//print coords to text box
msg = "";
for (var i = 0; i < coords.length; i++) {
msg = msg.concat("(", + coords[i][0] + "," + coords[i][1] + ")\n");
}
msg += "\n";
printMSG(msg);
//ratios for points to move as axes change
var xRatio = graphWidth / xMax;
var yRatio = graphHeight / yMax;
//draw points
for (var i = 0; i < coords.length; i++) {
if (showPoints) {
ctx.fillRect(axesOffset + (xRatio * coords[i][0]) - pointSize/2,
canvasHeight - axesOffset - (yRatio * coords[i][1]) - pointSize/2,
pointSize, pointSize);
}
if (showCoords) {
ctx.fillText("(" + coords[i][0] + ", " + coords[i][1] + ")", (xRatio * coords[i][0]) + axesOffset + pointSize/2, canvasHeight - axesOffset - (yRatio * coords[i][1]) + pointSize/2);
}
}
}
//redraw axes
function redrawAxes() {
xMax = parseFloat(document.getElementById("xAxisLength").value);
yMax = parseFloat(document.getElementById("yAxisLength").value);
numAxisMarkers = parseInt(document.getElementById("numMarkers").value);
paintCanvas();
}
//set labels
function setLabels() {
title = document.getElementById("titleText").value;
xLabel = document.getElementById("xAxisText").value;
yLabel = document.getElementById("yAxisText").value;
paintCanvas();
}
//set options
function setOptions() {
showBorder = document.getElementById("borderBox").checked;
showCoords = document.getElementById("coordBox").checked;
showGrid = document.getElementById("gridBox").checked;
showLines = document.getElementById("lineBox").checked;
showPoints = document.getElementById("pointBox").checked;
paintCanvas();
}
//reset coordinates and canvas
function reset() {
coords = new Array();
title = "";
xLabel = "";
yLabel = "";
paintCanvas();
}
//erase console and print new message
function printMSG(msg) {
document.getElementById("console").value = "";
document.getElementById("console").value = document.getElementById("console").value + msg + "\n";
}