Quantcast
Channel: User i alarmed alien - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by i alarmed alien for How to add text to svg circle in d3

$
0
0

There are numerous ways to add text labels to circles. In your code, you've added title elements to the circles, which usually show up as tooltips when you hover over the element. Unlike title elements, text elements cannot be added as children of the circle elements. One common way to handle them is to use g elements to group together the circle and the related text, so that you can then perform any transformations (or removals, etc.) on the g instead of having to apply them separately to text and circle.

To convert your code sample, first, I've altered the selectAll / enter code to act on g elements instead of circles:

const node = svg  [...]  .selectAll('.circle')  .data(nodes)  .enter()  .append('g')  // for each item in nodes, add <g class='circle'>  .classed('circle', true)

You can then append the circle and text elements to node:

node  .append("circle")  .attr('r', 5)node  .append("text")  .text(d => "Node: "+ d.id)

See the code snippet for a full example.

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>

Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>