chartjs 作圖初探

如果要作圖,Excel 幾乎可以滿足百分之90以上的需求,如果作圖又要放到網路上,那只能靠網頁工具,這類選擇其實不少,有開源的工具,也有付費工具。

最近看到 chartjs,基本的圖,它都能做。
你自已有網站可以用,沒有網站,離線的時侯還是可以用(那為何不用Excel ;) )。
做出來的圖好看。
做出來的圖可以和使用者互動。
概念簡單容易上手。

以折線圖來說(line.html):
以往 Excel 做圖的時侯,就是拉一拉資料的範圍,插入折線圖就行,但是網頁的話,必須的指定作圖所需要的元素,這些元素不外乎:標籤(有幾個點、大致上就有幾個標籤)、值(有幾個點、大致上就有幾個值)。



回到 chartjs 下載之後解壓縮會看到一個 sample 的資料夾,line.html 用文字編輯器(如:notepad、notepad++)打開,會看到一堆火星文一般的文字,找到這段編碼(關鍵字 lineChartData),把資料餵到相應的位置就行:
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
},
{
label: "My Second dataset",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]

}


參數設定(餵資料):
整個 lineChartData {}的範圍表示作這個圖的所有參數

X軸的標籤:記得標籤的名字放在 "" 的中間,逗號分隔。
labels : ["January","February","March","April","May","June","July"]


其中,值的部份,是 dataset[] 控制,每個{}的範圍代表作一條線的所有參數。
第一條線的名字:也是放在 "" 的中間
label: "My First dataset",

接下來的幾行的參數都是調顏色的:有興趣改變點和線的顏色的就在這裏調數字,我的美術細胞早就死光了@@"跳過 
fillColor,strokeColor, pointColor, pointStrokeColor, pointHighlightFill, pointHighlightStroke

畫折線的值:要和標籤的順序相對應,逗號分隔
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]


以上圖 Excel 的表格為例,改完之後 line.html 的 lineChartData 會長成以下這個樣子(改動處以下底線及顏色標示)。

var lineChartData = {
labels : ["牛仔褲","襯衫","外套"],
datasets : [
{
label: "價格",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [1200,1100,2400]
}
]

}

存檔後 line.html 點2下就會在瀏覽器開啟做好的圖

開心
收工

留言

這個網誌中的熱門文章

使用 Excel 計算2個地點之間的直線距離

LINE 儲存的檔案傳到 email 不方便 很不方便 非常不方便 但是有解的筆記

Excel 巨集合併多個 Excel 檔案