1. 程式人生 > >D3.js 柱形圖

D3.js 柱形圖

let dataset = [50, 43, 120, 87, 99, 167, 300]; // svg繪製區域的寬度 let width = 400; // svg繪製區域的高度 let height = 400; // 選擇body let svg = d3.select('body') // 新增svg .append('svg') // 設定svg的寬度屬性 .attr('width', width) // 設定svg的高度屬性
.attr('height', height); // 定義上下左右的邊距 let padding = { top: 20, right: 20, bottom: 20, left: 20 }; // 矩形所佔寬度(包括百空), 單位畫素 let rectStep = 35; // 矩形所佔寬度(不包括百空), 單位畫素 let rectWidth = 30; // 選擇所有rect let
rect = svg.selectAll('rect') // 繫結資料 .data(dataset) // 獲取enter部分 .enter() // 新增rect元素, 使其與繫結資料的長度一致 .append('rect') // 設定眼色為steelblue .attr('fill', 'steelblue') // 設定矩形的x座標 .attr('x', function (d, i) { // svg左內邊距 每個矩形的位置
return padding.left + i * rectStep }) // 設定矩形的y座標 .attr('y', function (d) { return height - padding.bottom - d; }) // 設定矩形的寬度 .attr('width', rectWidth) // 設定矩形的高度 .attr('height', function (d) { return d; }); // 接下來為矩形新增標籤文字, 方法與新增rect一樣,先用selectall()選擇一個空集,然後再為選擇集denter部分新增足夠數量的text元素。 let text = svg.selectAll('text') // 繫結資料 .data(dataset) // 獲取enter部分 .enter() // 新增text元素,使其與繫結陣列的長度一致 .append('text') // 設定文字填充色 .attr('fill', 'white') // 設定字型大小 .attr('font-size', '14px') // 後續為文字設定為矩形正中間 .attr('text-anchor', 'middle') // 設定x的與矩形一樣 .attr('x', function (d, i) { return padding.left + i * rectStep; }) // 設定y的與矩形一樣 .attr('y', function (d) { return height - padding.bottom -d; }) .attr('dx', rectWidth / 2) .attr('dy', '1em') // 輸出文字 .text(function (d) { return d; })