1 // Use this as a template for new Gallery entries.
5 name
: 'Function Plotter',
6 title
: 'Define your data with functions',
7 setup
: function(parent
) {
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)];",
13 "<b>Preset functions:</b> <select id='presets'>",
14 "<option selected id='custom'>(custom)</option>",
15 "<option id='id'>Identity</option>",
16 "<option id='sine'>Sine Wave</option>",
17 "<option id='taylor'>Taylor series</option>",
18 "<option id='sawtooth'>Sawtooth</option>",
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>",
26 "<div id='graph_div' style='width:600px; height:300px;'></div>"].join("\n");
30 var select
= document
.getElementById("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}' ]
37 select
.onchange
= function() {
38 var sel
= select
.selectedIndex
;
39 var id
= select
.options
[sel
].id
;
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];
48 var plotButton
= document
.getElementById("plot");
49 var plot
= function() {
50 var eq
= document
.getElementById("eq").value
;
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
;
60 for (var i
= 0; i
< width
; i
++) {
65 for (var j
= 0; j
< y
.length
; j
++) {
74 g
= new Dygraph(graph
, data
);
76 plotButton
.onclick
= plot
;