[英]How to add text to svg circle in d3
我有以下代码,我想在圈子中添加文字。 我怎么可能 我看过这些可能的重复项
const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.enter().append("line")
.attr("stroke-width", d => Math.sqrt(d.value));
// link.append("title").text(d => d.value);
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", d => color(d.group))
.call(drag(simulation));
node.append("title").text(d => "Node: " + d.id);
function ticked() {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
}
有多种将文本标签添加到圈子的方法。 在代码中,您已将title
元素添加到圈子中,当您将鼠标悬停在元素上时,通常会显示为工具提示。 与title
元素不同,文本元素不能添加为circle
元素的子元素。 处理它们的一种常用方法是使用g
元素将circle
和相关的text
组合在一起,以便随后可以对g
进行任何转换(或删除等),而不必将它们分别应用于text
和circle
。
要转换您的代码示例,首先,我更改了selectAll
/ enter
代码,使其作用于g
元素而不是圆形:
const node = svg
[...]
.selectAll('.circle')
.data(nodes)
.enter()
.append('g') // for each item in nodes, add <g class='circle'>
.classed('circle', true)
然后,您可以将circle
和text
元素附加到node
:
node
.append("circle")
.attr('r', 5)
node
.append("text")
.text(d => "Node: " + d.id)
有关完整示例,请参见代码段。
var nodes = [{ "x": 80, "y": 60, id: 'foo' }, { "x": 20, "y": 70, id: 'bar' }, { "x": 40, "y": 40, id: 'baz' }, { "x": 50, "y": 90, id: 'bop' }]; const svg = d3.select('svg') const node = svg .append("g") .attr("stroke", "#fff") .attr("stroke-width", 1.5) .selectAll(".circle") .data(nodes) .enter() .append('g') .classed('circle', true) .attr('transform', d => 'translate(' + dx + ',' + dy + ')'); node .append("circle") .attr("r", 5) .attr("fill", 'deepskyblue') // .call(drag(simulation)); node .append("text") .classed('circleText', true) .attr('dy', '0.35em') .attr('dx', 5) .text(d => "Node: " + d.id);
svg .circleText { font-family: Helvetica, Arial, sans-serif; font-size: 12px; fill: black; stroke-width: 0; }
<script src="http://d3js.org/d3.v5.js"></script> <svg width="200" height="200"></svg>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.