主题
D3.js
提示
当前版本:v7
简介
D3.js(Data-Driven Documents) 是一个基于 JavaScript 的可视化库,常用于创建数据驱动的动态和交互式图表。
特点:
- 采用 数据驱动 方式绑定数据与 DOM
- 基于 SVG、Canvas、HTML 进行可视化渲染
- 提供强大的 数据转换、动画 和 交互 支持
安装
CDN
html
<script src="https://d3js.org/d3.v7.min.js"></script>
npm
sh
npm install d3
核心概念
选择元素(Selection)
D3 使用 d3.select()
或 d3.selectAll()
选择 DOM 元素:
js
d3.select('p').style('color', 'red') // 选中第一个 <p> 并修改颜色
绑定数据(Data Binding)
data()
方法将数据绑定到选中的元素:
js
const data = [10, 20, 30]
d3.select('body')
.selectAll('p')
.data(data)
.enter()
.append('p')
.text(d => `数据值: ${d}`)
SVG 基础
D3 主要通过 SVG 绘制图表,如 circle
、rect
、line
等。
js
const svg = d3.select('body').append('svg').attr('width', 500).attr('height', 300)
svg.append('circle').attr('cx', 100).attr('cy', 100).attr('r', 50).attr('fill', 'blue')
比例尺(Scales)
D3 提供 scaleLinear()
、scaleOrdinal()
等方法,将数据映射到像素。
js
const scale = d3
.scaleLinear()
.domain([0, 100]) // 数据范围
.range([0, 500]) // 映射范围
console.log(scale(50)) // 250
轴(Axes)
D3 提供 d3.axisBottom()
、d3.axisLeft()
等用于绘制坐标轴。
js
const xScale = d3.scaleLinear().domain([0, 100]).range([0, 500])
const xAxis = d3.axisBottom(xScale)
d3.select('svg').append('g').attr('transform', 'translate(50, 250)').call(xAxis)
过渡(Transitions)
D3 可以使用 .transition()
创建动画效果。
js
d3.select('circle').transition().duration(1000).attr('r', 80)
事件处理
D3 支持鼠标、触摸等事件。
js
d3.select('circle')
.on('mouseover', function () {
d3.select(this).attr('fill', 'orange')
})
.on('mouseout', function () {
d3.select(this).attr('fill', 'blue')
})
常见可视化案例
绘制柱状图
js
const data = [40, 80, 150, 100, 60]
const svg = d3.select('body').append('svg').attr('width', 500).attr('height', 300)
svg
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', (d, i) => i * 60)
.attr('y', d => 300 - d)
.attr('width', 50)
.attr('height', d => d)
.attr('fill', 'teal')
绘制折线图
js
const lineData = [
{ x: 10, y: 50 },
{ x: 50, y: 80 },
{ x: 90, y: 30 },
{ x: 130, y: 100 },
]
const lineGenerator = d3
.line()
.x(d => d.x)
.y(d => d.y)
svg.append('path').datum(lineData).attr('d', lineGenerator).attr('stroke', 'blue').attr('fill', 'none')
绘制散点图
js
const scatterData = [
{ x: 30, y: 40 },
{ x: 80, y: 90 },
{ x: 120, y: 50 },
]
svg
.selectAll('circle')
.data(scatterData)
.enter()
.append('circle')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', 5)
.attr('fill', 'red')
进阶功能
数据交互
D3.js 可以通过 brush
实现数据筛选。
js
const brush = d3.brush().on('brush end', event => {
console.log(event.selection)
})
svg.append('g').call(brush)
组合 ECharts
D3 可用于数据预处理,然后传递给 ECharts 进行渲染。
js
const processedData = d3
.nest()
.key(d => d.category)
.entries(rawData)
const option = {
series: [{ type: 'bar', data: processedData }],
}