1

我有以下代码,我想在圆圈中添加文字。我怎样才能使它成为可能;我已经查看了这些可能的重复项

在 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);
}
4

1 回答 1

4

有多种方法可以向圆圈添加文本标签。在您的代码中,您已将title元素添加到圆圈中,当您将鼠标悬停在元素上时,这些元素通常会显示为工具提示。与title元素不同,文本元素不能作为元素的子circle元素添加。处理它们的一种常见方法是使用元素将和 相关g的 组合在一起,这样您就可以在 上执行任何转换(或删除等),而不必将它们分别应用于和。circletextgtextcircle

要转换您的代码示例,首先,我更改了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)

然后,您可以将circleandtext元素附加到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(' + d.x + ',' + d.y + ')');

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>

于 2018-10-11T08:17:12.980 回答