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