-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot-line.html
More file actions
118 lines (100 loc) · 3.3 KB
/
plot-line.html
File metadata and controls
118 lines (100 loc) · 3.3 KB
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
<link rel="import" href="../polymer/polymer.html">
<dom-module id="plot-line">
<template>
<style>
:host {
display: block;
width: 100%;
height: 100%;
position: absolute;
top: 0;
bottom: 0;
}
#content-area {
display: block;
}
</style>
</template>
<script>
var linspace = function(start, stop, nsteps) {
delta = (stop-start)/(nsteps-1)
return d3.range(nsteps).map(function(i){return start+i*delta;});
}
Polymer({
is: 'plot-line',
properties: {
formula: {
type: String,
value: "0"
},
lineColor: {
type: String,
value: "blue"
},
lineWidth: {
type: Number,
value: 2
},
lineDashArray: {
type: String,
value: "1, 0"
},
steps: {
type: Number,
value: 200
}
},
computeXMin: function(){
return this.root.host.parentNode.computeXMin();
},
computeXMax: function(){
return this.root.host.parentNode.computeXMax();
},
computeYMin: function(){
return this.root.host.parentNode.ymin;
},
computeYMax: function(){
return this.root.host.parentNode.ymax;
},
drawLine: function(){
// Calculate width and height.
let w = Polymer.dom(this.root).node.host.offsetWidth;
let h = Polymer.dom(this.root).node.host.offsetHeight;
var x_scale = d3.scaleLinear()
.domain([this.computeXMin(), this.computeXMax()])
.range([0, w - 50]);
var y_scale = d3.scaleLinear()
.domain([this.computeYMin(), this.computeYMax()])
.range([h - 40, 0]);
// Parsing de la formula (string) a una funcion de javascript evaluable
var f = math.compile(this.formula);
var points = linspace(this.computeXMin(), this.computeXMax(), this.steps);
var lineData = points.map(function(d){
return {"x": d, "y": f.eval({x: d})};
});
var lineFunction = d3.line()
.curve(d3.curveCatmullRom)
.x(function(d) {return x_scale(d.x);})
.y(function(d) {return y_scale(d.y);});
var svgContainer = d3.select(Polymer.dom(this.root).node.host) // We use Polymer $ selector
.append("svg") // to get the actual DOM element.
.attr("width", w) // Using "#..." will be bugged.
.attr("height", h);
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", this.lineColor)
.attr("stroke-width", this.lineWidth)
.style("stroke-dasharray", this.lineDashArray)
.attr("fill", "none")
.attr("transform", "translate(25, 15)");
},
// Make line when attached or attribute changes.
attached: function() {
this.drawLine();
},
attributeChanged: function(){
this.drawLine();
}
});
</script>
</dom-module>