Merge pull request #139 from klausw-g/stacked-NaN
[dygraphs.git] / gallery / plotter.js
1 Gallery.register(
2 'plotter',
3 {
4 name: 'Function Plotter',
5 title: 'Define your data with functions',
6 setup: function(parent) {
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'>",
13 "<option selected id='custom'>(custom)</option>",
14 "<option id='id'>Identity</option>",
15 "<option id='sine'>Sine Wave</option>",
16 "<option id='taylor'>Taylor series</option>",
17 "<option id='sawtooth'>Sawtooth</option>",
18 "</select>",
19 "</p>",
20 "",
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>",
24 "",
25 "<div id='graph_div' style='width:600px; height:300px;'></div>"].join("\n");
26
27 },
28 run: function() {
29 var select = document.getElementById("presets");
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 };
36 select.onchange = function() {
37 var sel = select.selectedIndex;
38 var id = select.options[sel].id;
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
47 var plotButton = document.getElementById("plot");
48 var plot = function() {
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 }
75 plotButton.onclick = plot;
76 plot();
77 }
78 });