-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgnuplot.js
125 lines (98 loc) · 2.51 KB
/
gnuplot.js
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
119
120
121
122
123
124
125
var log = console.log
var spawn = require('child_process').spawn
/** EXEMPLE:
var plot = gnuplot()
plot.plot([{
data:[[x0,y0],[x1,y1],[x2,y2]]
},{
title:"data2",
style:"boxes",
color:"red",
data:[[x0,y0],[x1,y1],[x2,y2]]
},{
title:"data3",
style:"lines",
color:"#00FF00",
data:[[x0,y0],[x1,y1],[x2,y2]]
}])
*/
function convertArray(arr){
//[[x0,y0],[x1,y1],[x2,y2], ...]
return arr.map(function(p){
return p.join(" ") + "\n"
}).join("")
}
gnuPlot = function () {
var plotObj = spawn('gnuplot')
var errBuff = ""
//tidy up stderr
plotObj.stderr.on('data', function(e){
errBuff += e
if(errBuff.indexOf("\n")){
var lines = errBuff.split("\n")
errBuff = lines.pop()
log( "[GNUPLOT ERR]" + lines.join("\n") )
}
})
plotObj.print = function (d) {
// log(d)
plotObj.stdin.write(d)
return plotObj
}
plotObj.set = function (options) {
var str = Object.keys(options).map(function(key){
var vals = options[key]
if(vals){
if(!Array.isArray(vals)){
vals = [vals]
}
return vals.map(function(val){
if(val === true)
return "set " + key + "\n"
else
return "set " + key + " " + val + "\n"
}).join("")
} else {
return "unset " + key + "\n"
}
}).join("")
plotObj.print(str)
return plotObj
}
function plotString (data) {
var bodyArr = []
var head = data.map(function(field, i){
var r = []
if(field.data.constructor === String){
r.push(field.data)
} else {
r.push("'-'")
bodyArr.push( convertArray(field.data) + "e\n" )
}
["using", "smooth", "axes", "bins"].forEach( (keyword) => {
if(field[keyword] !== undefined) r.push(keyword+" "+field[keyword])
})
if(field.title !== undefined) r.push("title \""+field.title+"\"")
else r.push("title \""+ i +"\"")
r.push("with")
if(field.style) r.push(field.style)
else r.push("lines")
if (field.color ) r.push("linecolor "+field.color)
else if(field.rgbcolor) r.push("linecolor rgbcolor \""+field.rgbcolor+"\"")
return r.join(" ")
}).join(", ") + "\n"
var body = bodyArr.join("")
return head + body
}
plotObj.plot = function(d){
plotObj.print("plot "+plotString(d))
return plotObj
}
plotObj.splot = function(d){
plotObj.print("splot "+plotString(d))
return plotObj
}
plotObj.end = plotObj.stdin.end.bind(plotObj.stdin)
return plotObj
}
module.exports = gnuPlot