REFACTORING: Added exception if no y axis has the independentTicks
[dygraphs.git] / gallery / plotter.js
CommitLineData
c1f22b5a
RK
1Gallery.register(
2 'plotter',
3 {
d0d1f76b
RK
4 name: 'Function Plotter',
5 title: 'Define your data with functions',
c1f22b5a 6 setup: function(parent) {
605b6119
RK
7 parent.innerHTML = [
8 "<p><b>Equation: </b><br/>",
9 "<textarea cols='80' rows='10' id='eq'>function(x) {",
10 " return [0.1 * x, 0.1 * x + Math.sin(x), 0.1*x + Math.cos(x)];",
11 "}</textarea><br/>",
12 "<b>Preset functions:</b> <select id='presets'>",
04c0ae73 13 "<option selected id='custom'>(custom)</option>",
605b6119
RK
14 "<option id='id'>Identity</option>",
15 "<option id='sine'>Sine Wave</option>",
16 "<option id='taylor'>Taylor series</option>",
04c0ae73 17 "<option id='sawtooth'>Sawtooth</option>",
605b6119
RK
18 "</select>",
19 "</p>",
20 "",
10eef8e9
RK
21 "<p><b>x range: </b> <input type='text' width='5' id='x1' value='-10' />",
22 "to <input type='text' width='5' id='x2' value='10' /></p>",
23 "<p><button id='plot'>Plot</button></p>",
605b6119 24 "",
10eef8e9 25 "<div id='graph_div' style='width:600px; height:300px;'></div>"].join("\n");
c1f22b5a
RK
26
27 },
28 run: function() {
3c10a0f3 29 var select = document.getElementById("presets");
04c0ae73
RK
30 var presets = {
31 'id': [ -10, 10, 'function(x) {\n return x;\n}' ],
32 'sine': [ -10, 10, 'function(x) {\n return Math.sin(x);\n}' ],
33 'taylor': [ -3, 3, 'function(x) {\n return [Math.cos(x), 1 - x*x/2 + x*x*x*x/24];\n}' ],
34 'sawtooth': [-10, 10, 'function(x) {\n var y = 0;\n for (var i = 1; i < 20; i+=2) {\n y += Math.sin(i * x)/i;\n }\n var final = 1 - 2*(Math.abs(Math.floor(x / Math.PI)) % 2);\n return [4/Math.PI * y, final];\n}' ]
35 };
3c10a0f3
RK
36 select.onchange = function() {
37 var sel = select.selectedIndex;
38 var id = select.options[sel].id;
c1f22b5a
RK
39
40 if (id == "custom") { return; }
41 document.getElementById("x1").value = presets[id][0];
42 document.getElementById("x2").value = presets[id][1];
43 document.getElementById("eq").value = presets[id][2];
44 plot();
45 }
46
3c10a0f3
RK
47 var plotButton = document.getElementById("plot");
48 var plot = function() {
c1f22b5a
RK
49 var eq = document.getElementById("eq").value;
50 eval("fn = " + eq);
51
52 var graph = document.getElementById("graph_div");
53 var width = parseInt(graph.style.width);
54 var x1 = parseFloat(document.getElementById("x1").value);
55 var x2 = parseFloat(document.getElementById("x2").value);
56 var xs = 1.0 * (x2 - x1) / width;
57
58 var data = [];
59 for (var i = 0; i < width; i++) {
60 var x = x1 + i * xs;
61 var y = fn(x);
62 var row = [x];
63 if (y.length > 0) {
64 for (var j = 0; j < y.length; j++) {
65 row.push(y[j]);
66 }
67 } else {
68 row.push(y);
69 }
70 data.push(row);
71 }
72
73 g = new Dygraph(graph, data);
74 }
04c0ae73 75 plotButton.onclick = plot;
3c10a0f3 76 plot();
c1f22b5a
RK
77 }
78 });