D3.js
D3.js 是一個用於基於資料操縱 HTML 的 JavaScript 庫。
如何使用 D3.js?
要在網頁中使用 D3.js,請新增指向該庫的連結
<script src="//d3js.org/d3.v3.min.js"></script>
D3.js 易於使用。
此指令碼選擇 body 元素並追加一個帶有文字“Hello World!”的段落。
d3.select("body").append("p").text("Hello World!");
散點圖
示例
// 設定尺寸
const xSize = 500;
const ySize = 500;
const margin = 40;
const xMax = xSize - margin*2;
const yMax = ySize - margin*2;
// 建立隨機點
const numPoints = 100;
const data = [];
for (let i = 0; i < numPoints; i++) {
data.push([Math.random() * xMax, Math.random() * yMax]);
}
// 將 SVG 物件附加到頁面
const svg = d3.select("#myPlot")
.append("svg")
.append("g")
.attr("transform","translate(" + margin + "," + margin + ")");
// X 軸
const x = d3.scaleLinear()
.domain([0, 500])
.range([0, xMax]);
svg.append("g")
.attr("transform", "translate(0," + yMax + ")")
.call(d3.axisBottom(x));
// Y 軸
const y = d3.scaleLinear()
.domain([0, 500])
.range([ yMax, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// 點
svg.append('g')
.selectAll("dot")
.data(data).enter()
.append("circle")
.attr("cx", function (d) { return d[0] } )
.attr("cy", function (d) { return d[1] } )
.attr("r", 3)
.style("fill", "Red");