1

I need to create a visualization as shown in the image:

enter image description here

A rectangle box with text inside it and network around the box. I am trying to use D3, and I am stuck at the first step of putting text inside the rectangle. I found out that we cannot put text inside a rectangle or circle in d3. Is there a container or something like that in d3 to put text inside and make the network around them?

Michael Rovinsky
  • 6,807
  • 7
  • 15
  • 30

1 Answers1

0

You cannot create a text element under a <rect> / <circle> / <polygon> / <path>...

Add a <g> element. Then, add a <rect> and a <text> under the <g>:

const svg = d3.select('svg');

const g = svg.append('g')
  .attr('transform', 'translate(100,50)');

g.append('rect')
  .attr('x', -60)
  .attr('y', -40)
  .attr('width', 120)
  .attr('height', 80)
  
g.append('text')
  .text('This is a text')
  .attr('text-anchor', 'middle')
  .attr('alignment-baseline', 'middle');
  

  
rect {
  fill: none;
  stroke: black;
}

text {
  font-family: "Ubuntu";
  font-size: 16px;
  fill: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg />
Michael Rovinsky
  • 6,807
  • 7
  • 15
  • 30