title: 【D3.js】2.3-向散点图的 Circles 添加标签
date: 2022-12-02 15:34
tags: [JavaScript,CSS,HTML,D3.js,SVG]
跟条形图一样,添加标签来增加图形的表现力。
一、学习目标
- 通过什么元素给circle添加标签
text
二、题目
使用 text 元素标记散点图上的每个点。 标签的文本应该是用逗号和空格分隔的两个值。 例如,第一个点的标签是 34, 78。 设置 x 属性,使其比 circle 上的 cx 属性的值多 5 个单位。 设置 y 属性的方式与 circle 上的 cy 值相同。
三、通关代码
<body>
<script>
const dataset = [
[ 34, 78 ],
[ 109, 280 ],
[ 310, 120 ],
[ 79, 411 ],
[ 420, 220 ],
[ 233, 145 ],
[ 333, 96 ],
[ 222, 333 ],
[ 78, 320 ],
[ 21, 123 ]
];
const w = 500;
const h = 500;
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", (d, i) => d[0])
.attr("cy", (d, i) => h - d[1])
.attr("r", 5);
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
// 在这行下面添加代码
.text((d,i)=>{return d.join(", ")})
.attr("x", (d, i) => d[0]+5)
.attr("y", (d, i) => h - d[1])
// 在这行上面添加代码
</script>
</body>