D3学习笔记(一)
B站观看《数据可视化编程-使用D3.js》笔记
资源
视频链接:https://www.bilibili.com/video/av497590991/
课件与代码:https://github.com/Shao-Kui/D3.js-Demos
svg文档:https://developer.mozilla.org/zh-CN/docs/Web/SVG
引用d3资源:https://d3js.org/d3.v7.min.js
笔记
01.HelloWorld(有前端基础可跳过)
- 视频介绍了Flask服务搭建,但根据弹幕伙伴提示还是选择了使用VSCode搭建服务,安装了Live Server(参考:https://blog.51cto.com/u_15302032/3067397)
02.操控SVG
- select(查询单个元素)、selectAll(查询多个元素)、层级查询
- attr:id、class、x、y、cx、cy、fill、stroke、height、width、r、transform……
- +(strValue)转换,如let value = +(‘233.666’)
- 父节点属性会影响子节点,子节点属性会相对于父节点
- append,remove
- 比例尺:用于把实际的数据空间映射到屏幕的空间,经常同时传给坐标轴与数据
(比例尺返回一个函数)
//Linear 线性比例尺(连续)
const xScale = d3.scaleLinear().domain([min_d, max_d]).range([min,max])
//Band 条带比例尺(离散)
const yScale = d3.scaleBand().domain(list).range([min,max]).padding(p)
//example
const myScale = d3.scaleLinear().domain([0,10]).range([-1000,1000])
console.log(myScale(5)) //0
console.log(myScale(9)) //800
- 最大值函数:d3.max(data, d=>d.value)
- 实例:
1.比例尺:domain、range参数都是数组
// 比例尺
const xScale = d3.scaleLinear().domain([0, d3.max(data, d=>d.value)]).range([0, innerWidth])
const yScale = d3.scaleBand().domain(data.map(d => d.name)).range([0, innerHeight]).padding(0.1)
2.坐标轴:
// 坐标轴
const xAxis = d3.axisBottom(xScale)
const yAxis = d3.axisLeft(yScale)
g.append('g').call(xAxis).attr('transform', `translate(0, ${innerHeight})`)
g.append('g').call(yAxis)
3.画图:xScale(item.value),attr(‘y’, yScale(item.name))使用比例尺函数映射,yScale.bandwidth()提供条带宽度方法
// 图
data.forEach(item => {
g.append('rect')
.attr('width',xScale(item.value))
.attr('height',yScale.bandwidth())
.attr('fill','green')
.attr('y', yScale(item.name))
})
4.其他:如自动生成的class -tick
// 设置样式
d3.selectAll('.tick text').attr('font-size', '2em')
// 添加标题
g.append('text').text('Members oc CSCG')
.attr('transform',`translate(${innerWidth/2}, 0)`)
.attr('text-anchor','middle')
.attr('font-size','3em')
(未完)