D3.js

D3.js là một thư viện JavaScript để thao tác HTML dựa trên dữ liệu.

Làm thế nào để sử dụng D3.js?

Để sử dụng D3.js trong trang web của bạn, hãy thêm một liên kết đến thư viện:

<script src="//d3js.org/d3.v3.min.js"></script>

D3.js rất dễ sử dụng.

Tập lệnh này chọn phần tử nội dung và nối một đoạn với văn bản "Hello World!":

d3.select("body").append("p").text("Hello World!");


Lô phân tán

050100150200250300350400450500050100150200250300350400450500

Thí dụ

// Set Dimensions
const xSize = 500;
const ySize = 500;
const margin = 40;
const xMax = xSize - margin*2;
const yMax = ySize - margin*2;

// Create Random Points
const numPoints = 100;
const data = [];
for (let i = 0; i < numPoints; i++) {
  data.push([Math.random() * xMax, Math.random() * yMax]);
}

// Append SVG Object to the Page
const svg = d3.select("#myPlot")
  .append("svg")
  .append("g")
  .attr("transform","translate(" + margin + "," + margin + ")");

// X Axis
const x = d3.scaleLinear()
  .domain([0, 500])
  .range([0, xMax]);

svg.append("g")
  .attr("transform", "translate(0," + yMax + ")")
  .call(d3.axisBottom(x));

// Y Axis
const y = d3.scaleLinear()
  .domain([0, 500])
  .range([ yMax, 0]);

svg.append("g")
  .call(d3.axisLeft(y));

// Dots
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");