d3
javascript
長條圖
[D3.js] 繪製長條圖
2017/12/19 14:55:38
0
2233
[D3.js] 繪製長條圖
簡介 |
D3.js 提供了一個強大函式庫可以替我們計算並繪製各種圖表,在此以常用的長條圖形來了解 d3的基本用法 。 |
作者 |
湯菀鈺 |
介紹
D3.js 是一套 Javascript 函式庫,可以整合數據並繪製各種圖表,以下使用常用的長條圖來初試d3的功能。
![](/tpu/File/html/201712/20171215031621/images/20171215023838.png)
先在 HTML 中引入 D3.js 的程式碼
![](/tpu/File/html/201712/20171215031621/images/20171214035024.png)
使用d3的選擇器來操控HTML容器
- d3.select("body")就代表選到了html裡的body tag
- 接下來直接使用d3操作選到的容器
- span.text("hello world")就是在容器裡輸入文字
- .style("font-size", "24px")則是將style樣式套用至容器內
![](/tpu/File/html/201712/20171215031621/images/20171214040014.png)
選擇器整合數據資料
為了能大量的產生所需的介面資料,先建立一組陣列數據,在此以各分店營收數據為範例,
測試結果看的出來,d3已自動將陣列取得的資料轉換成介面所需要的tag內容。
其中div_set.text 裡使用 function(d,i) 的方式動態取得陣列裡所包含的值。
- d[0] 取回的是陣列中的店名
- d[1]取回的是營收的金額
- i 則是陣列的索引編號。
var death_rate = [['台中分店',25],['台北分店',16],['高雄分店',30],['汐止分店',20],['板僑分店',40]];
var div_data_bind = d3.select("body").selectAll("div").data(death_rate);
div_set = div_data_bind.enter().append("div");
div_data_bind.exit().remove();
div_set.text(function(d,i) {
return d[0]+'營收('+d[1]+'萬)';
});
![](/tpu/File/html/201712/20171215031621/images/20171214040752.png)
調整容器樣式
為容器加上background 的style設定:
div_set.style("background", "#ffcc00");
![](/tpu/File/html/201712/20171215031621/images/20171214041549.png)
長條圖樣式
為了表現出長條圖的效果,在此設定每個容器的width等於營收的數據。
div_set.style("width", function(d,i) {
return (d[1] * 10)+"px";
});
其中 d[1] 將取得陣列中的營收數字,d3的容器選擇後,
皆可將第2個參數以function(d,i)的方式去變化使用。
![](/tpu/File/html/201712/20171215031621/images/20171214042115.png)
調整背景色
將原本單調的一個背景色,改成依各分店營收的量套用符合條件的顏色。
div_set.style("background", "#ffcc00");
改寫如下:
div_set.style("background", function(d,i){
if(d[1]<=20) return "red";
if(d[1]>=40) return "#33cc33";
return "#ffcc00";
});
設定小於等於20萬者套用紅色背景,高於40萬者套用綠色背景,其他分店則以黃色做為背景色。
![](/tpu/File/html/201712/20171215031621/images/20171214042621.png)
調整長條圖間距
目前每筆長條圖上下都沒有距離,可以搭配css的設定參數增加每個div的間距,
設定如下:
div_set.style("margin", "5px");
也可以搭配高度參數
div_set.style("height", "20px");
![](/tpu/File/html/201712/20171215031621/images/20171214043024.png)
完整程式碼
var death_rate = [['台中分店',25],['台北分店',16],['高雄分店',30],['汐止分店',20],['板僑分店',40]];
var div_data_bind = d3.select("body").selectAll("div").data(death_rate);
div_set = div_data_bind.enter().append("div");
div_data_bind.exit().remove();
div_set.text(function(d,i) {
return d[0]+'營收('+d[1]+'萬)';
});
div_set.style("height", "20px");
div_set.style("background", function(d,i){
if(d[1]<=20) return "red";
if(d[1]>=40) return "#33cc33";
return "#ffcc00";
});
div_set.style("margin", "5px");
div_set.style("width", function(d,i) {
return (d[1] * 10)+"px";
});