前端必知必会-D3.js


D3.js

D3.js 是一个用于处理 HTML 数据的 JavaScript 库。

D3.js 易于使用。

如何使用 D3.js?

要在网页中使用 D3.js,请添加指向库的链接:

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

此脚本选择 body 元素并附加一个带有文本“Hello World!”的段落:

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

散点图

0
50
100
150
200
250
300
350
400
450
500
0
50
100
150
200
250
300
350
400
450
500

示例

// 设置尺寸
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");

总结

本文介绍了D3.js的使用,如有问题欢迎私信和评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程岁月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值