###### tags: `JS 學徒特訓班`
# JS 學徒特訓班 30 C3.js 圖表整合筆記
題目:https://hackmd.io/Vp1FRGPMRymM7FOxaQ_srQ
### 載入js、css、外部資料
- [d3.js](https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js)
- [c3.js](https://c3js.org/examples.html)
- [長條圖](https://c3js.org/samples/chart_bar.html)
- [c3 的 css](https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.18/c3.min.css)
- [axios](https://github.com/axios/axios)
- [練習API](https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json)
### 定義資料與取得資料
```javascript=
var url = 'https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json';
var data = [];
axios.get(url)
.then(function(res){
data = res.data;
setData(data);//跑排序
render(columns,namelist);//進行圖表化
})
```
因為 c3.js 的資料呈現方式為
```javascript=
columns: [
["標題", 資料]
],
```
原始取得的資料呈現為
```javascript=
0: {id: "1", name: "廖洧杰(測試名稱)", process: "15%", checkpoint: {…}}
1: {id: "2", name: "Kun", process: "10%", checkpoint: {…}}
2: {id: "3", name: "Hung", process: "0%", checkpoint: {…}}
...
```
所以取得的資料必須重新組合
先將原有資料重新排序之後再取出組合
```javascript=
//增加定義的資料
let columns = ["完成率"];//參賽者完成率
let namelist = [];//參賽者姓名
//排序資料與取出資料放到新定義的陣列
function setData(data){
data.sort((a,b) => parseInt(b.process) - parseInt(a.process));
data.forEach((item,index)=>{
columns.push(item.process);//完成率陣列
namelist.push(item.name);
});
}
```
接下來進行 c3.js 資料視覺化
先在 html 裡面增加一個 div
```javascript=
<div id="chart"></div>
```
進行 c3.js 的資料建構(直接複製範本過來修改)
```javascript=
function render(columns,namelist){
var chart = c3.generate({
data: {
columns: [
[...columns],//將前面重新組成的完成率放入
],
type: 'bar',//使用的圖表類型
colors: {
完成率: "#9CCC65",
//這是指每一個陣列資料的顏色,而此處只有一個完成率的陣列
//["完成率", 45%, 45% ....]
//因此前面使用陣列的第一個 "完成率",後面指定顏色
},
axes: {//旋轉之後完成率會出現在最下方,所以在上方再新增另一個 Y 軸
完成率: 'y2'
}
},
bar: {
width: {
ratio: 0.1 //設定 bar 的寬度
}
},
size: {
height: namelist.length * 30, //調整圖表高度
},
axios: { //用來設定 x,y 軸
//上面的姓名資料會出現在 X 軸,但是總比數非常多,所以旋轉圖表
rotated: true,
//但是旋轉之後完成率會出現在最下方,所以在上方 data 要再新增另一個 Y 軸
x: {
type: "category",
//這裡是指用下方的 categories 來顯示 X 軸,也就是參賽者名稱
//只能使用 category 不能用其他字代替
//我在這邊卡好久才搞懂
//參考: https://c3js.org/samples/categorized.html
categories: namelist,
},
y: {
show: true, //下方 Y 軸顯示
label: {
text: "完成率%",
position: "outer-center", //名稱位置
},
},
y2: {
show: true, //上方 Y 軸顯示
label: {
text: "完成率%",
position: "outer-center", //名稱位置
},
}
}
});
}
```
- [data.colors](https://c3js.org/reference.html#data-colors)
- [增加另一個 Y 軸](https://c3js.org/reference.html#data-axes)
- [X Y 軸的設定](https://c3js.org/reference.html#axis-rotated)
- [axios.x.categories](https://c3js.org/samples/categorized.html)
- [axios 基本使用 & Config](https://ithelp.ithome.com.tw/articles/10212120)