[JS] 用C3.js來繪製圖表

[JS] 用C3.js來繪製圖表

前言

c3.js是一個免費開源的圖表套件,源自d3.js(操控SVG向量圖形進行資料視覺化的JavaScript程式庫),類似的套件還有ChartJS

C3.js 圖表整合文件

起手式

js必須載入兩支d3.js和c3.js

1
2
3
4
5
6
<!-- Load c3.css -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.18/c3.css">

<!-- Load d3.js and c3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.18/c3.js"></script>

在要建立圖表的地方插入,id可更改。

1
<div id="chart"></div>

接著初始化圖表,bindto設定對應的id名稱,就可以看到圖表畫面,接下來還有

1
2
3
4
5
6
7
8
9
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
}
});

起手式 線圖 DEMO

C3.js的各式圖表example

Customize Chart

這邊列舉了一些用法,官方文件中還有其他更詳細介紹搭配不同圖表,就不一一介紹了。

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
var chart = c3.generate({
bindto: "#chart",
data: {
columns: [
// 資料位置
["data1", 30, 200, 100, 400, 150, 250],
["data2", 50, 20, 10, 40, 15, 25],
["data3", 2000, 20, 10, 40, 15, 25]
],
axes: {
// 軸數增加第二個
data2: "y2"
},
// 圖型類型設定
types: {
data2: "bar", // 長條圖
data3: "spline" // 曲線圖
},
// 更改顏色設定
colors: {
data1: "#03A9F4",
data2: "#162F03",
data3: "#76FF03"
}
},
axis: {
rotated: false, //是否轉成橫向
x: {
type: "category",
categories: [2000, 2001, 2002, 2003, 2004, 2005], // x軸單位內容
label: {
text: "X Label", // x軸設定顯示名稱
position: "outer-left" //擺放位置
}
},
y: {
label: {
// y軸設定顯示名稱
text: "Y Label",
position: "outer-bottom"
},
tick: {
format: d3.format("$,") // 資料前增加$符號
}
},
y2: {
show: true,
label: {
text: "Y2 Label",
position: "outer-middle"
}
}
}
});

另外也可在CSS上使用class名稱 c3-line-[id] 來修改畫面

1
2
3
#chart .c3-line-data3 {
stroke-width: 5px;
}

客制設定 DEMO

長條圖 Bar Chart

這邊會以長條圖為例把js60第29天的資料串接改成以長條圖方式呈現,把api回傳的資料, 用forEach依選擇的排列方式,把名字和完課率依序傳入到各自的新陣列,再把完課率陣列綁定到c3js圖表的data.columns裡,而名字綁定到x軸的categories上,畫面便可呈現。

推薦延伸閱讀
TimCodingBlog

Author

KaiYun Cheng

Posted on

2020-11-05

Updated on

2024-04-13

Licensed under

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×