10分鐘學會Chart.js

10分鐘學會Chart.js

The scientist has a lot of experience with ignorance and doubt and uncertainty, and this experience is of very great importance, I think. - 理察·費曼


chart.js

  • Chart.js是一款彈性很高的圖表JavaScript library,
  • 支援基本常見的統計圖表類型 - 折線圖(line) , 長條圖(bar) , 雷達圖(radar) , 圓餅圖(pie & doughnut) , 圓面積圖(polarArea) , 氣泡圖(bubble) , 分布圖(scatter) , 混合圖形

使用Chart.js

  • 使用 Chart.js CDN
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
  • 載入Chart.js之後,我們可以先將要顯示圖表的位置加入一個canvas
1
<canvas id="myChart" width="400" height="400"></canvas>
  • Chart.js接受多種取得canvas的方式,也支援混合類型的圖表
1
2
3
4
var ctx = document.getElementById('myChart'); 
var ctx = document.getElementById('myChart').getContext('2d');
var ctx = $('#myChart');
var ctx = "myChart";

一般屬性設定

  • 畫布渲染大小(canvas.width.height不能用相對值表示,與顯示大小(canvas.style.width.height)相反
1
`<canvas height="40vh" width="80vw">` <!-- **無效的**值,畫布不會調整大小-->
  • Chart.js使用其父容器來更新畫布渲染顯示大小,此方法要求容器相對定位,並且只專用於圖表畫布
1
2
3
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="chart"></canvas>
</div>

基本範例

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
<canvas id="myChart" width="400" height="400"></canvas>

<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar', // 圖表類型
data: { // 顯示資料
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], //項目
datasets: [{ //圖表設置
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}, // 配置選項
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
legend: {
labels: {
// This more specific font property overrides the global property
fontColor: 'black',
fontSize: 16
}
}
}
});
</script>