0%

JS特訓-DAY30-C3.js 圖表整合

前言

嘗試用C3.js圖表呈現,看看誰的完課率最好,同時可以看出排名!

延續之前學習到如何使用 axios 串接 AJAX,並且使用 forEach 來選取所要的資料,並且這次透過 change 事件的判斷條件,使資料有排序功能。

本次練習使用此 API

起手式

基本認識可以看 C3.js 基本認識

取得資料

延續前面所使用的 sort() 與 axios 方法,結合 C3.js 圖表套件完成視覺化資料處理

  • 宣告 data 存放回傳資料用
  • 宣告 columns 變數要放入完成率的資料
  • 宣告 category 變數要放入參賽者姓名資料
  • 其中要執行兩個函式
let data;  
let columns = ['完成率'];  
let category = [];  
const dataUrl = 'https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json';  

axios.get(dataUrl).then((response) => {
  data = response.data;  
  console.log(data);  
  sortData(data);  
  load(columns, category);  
});  

以下說明函式內容

資料排序

改寫之前的篩選排序方法

  • 資料排序從完成率高到低
  • 取得完成率資料,取得小數點後兩位,並用百分比顯示,增加到圖表中的 columns
  • 將參賽者姓名資料,增加到 category 的空陣列中
function sortData(data) {
  data.sort((a, b) => parseFloat(b.process) - parseFloat(a.process));  

  data.forEach((item) => {
    columns.push(parseFloat(item.process) / 100);  
    category.push(item.name);  
  });  
}  

呈現在視覺資料中

  • 函式要帶入的參數就是完成率與參賽者資料。
  • columns 就是把宣告的變數項目與完成率資料展開放在一起。
  • colors 的屬性要與 columns 所帶入的 data 名稱相符,這邊為完成率,顏色使用色票,並使用字串形式。
  • size 的屬性設定圖表高度 *30px,不然會全部擠在一起,無法辨識。
  • axis 屬性增加 rotated 的原因是資料太多,改成橫向較好閱讀(所以 X 軸變成 Y 軸位置)。
  • categories 屬性帶入的就是宣告的參賽者變數 category。
  • label 為要帶入的標籤內容與位置。

更多設定可以查看官網 Reference

function load(columns, category) {
  var chart = c3.generate({
    bindto: "#chart",
    data: {
      columns: [
        [...columns] //完成率與資料展開
      ],
      axes: {
        完成率: "y2"
      },
      type: "bar", //圖表類型
      colors: {
        完成率: "#2196F3"
      }
    },
    size: {
      height: category.length * 30 //調整圖表高度
    },
    axis: {
      rotated: true, //轉成橫向
      x: {
        type: "category", // 左側 X 軸顯示
        categories: category, //參賽姓名資料
        label: {
          text: "參賽者姓名",
          position: "outer-center"
        }
      },
      y: {
        show: true, //下方 Y 軸顯示
        label: {
          text: "完成率%",
          position: "outer-middle" //名稱位置
        }
      },
      y2: {
        show: true, //上方 Y 軸顯示
        label: {
          text: "完成率%",
          position: "outer-middle" //名稱位置
        }
      }
    }
  });
}  

CodePen