Node.js 圖表處理 (3)

基本介紹

教學目標

透過 highcharts 套件實作圖表,呈現看劇的男生和女生比例資訊。

使用教學

chart.html

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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="http://library.leoyeh.me/css/bootstrap/bootstrap-3.3.1.min.css" rel="stylesheet"></link>
<link href="http://library.leoyeh.me/css/bootstrap/bootstrap-theme-3.3.1.min.css" rel="stylesheet"></link>
<script src="http://library.leoyeh.me/js/jquery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="http://library.leoyeh.me/js/highchart/highcharts.js" type="text/javascript"></script>
</head>
<body>
<center>
<div class="input-group">
<input type="text" class="form-control" id="keyword"></input>
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="generate">產生圖表</button>
</span>
</div>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</center>
<script>
$("button").click(function(){
var keyword = $("#keyword").val();
var url = "http://127.0.0.1:8080/query/"+keyword;
var options = {
chart: {
renderTo: 'container',
type: 'pie'
},
title: {
text: '男女比例'
},
yAxis: {
title: {
text: 'percent'
}
},
tooltip: {
pointFormat: '<b>{series.name}: </b>(point.y) {point.percentage:.1f} %'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}: </b>(point.y) {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{}]
};
$.getJSON(url, function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>

</body>
</html>

server.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
var express = require('express');
var app = express();
app.get("/query/:keyword",function(req, res) {

var keyword = req.params.keyword;
var query = [];
query["來自星星的你"] = [{
"gender":"female",
"count":"300"
},{
"gender":"male",
"count":"100"
}];
var data = query[keyword];
var chart_data = [];
if (data) {
try {
for (var n=0; n<data.length; n++) {
if (data[n].gender == "female") {
chart_data.push(["女生",parseInt(data[n].count)]);
}
if (data[n].gender == "male") {
chart_data.push(["男生",parseInt(data[n].count)]);
}
}
res.header('Access-Control-Allow-Origin', '*');
res.json(chart_data);
} catch(err) {
console.log(err)
}
} else {
res.header('Access-Control-Allow-Origin', '*');
res.json(chart_data);
}
});
var port = process.env.PORT || 8080;
app.listen(port);
console.log("http://127.0.0.1:" + port);

接著透過以下指令啟動資料 API 的伺服器。

1
$ node server.js

用瀏覽器開啟 chart.html 檔案進行測試。

相關資源