labels in circles with d3

Add labels to circle and change their scale so they fill the circle.

HTML

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400" height="300" style="background-color:#ccc"></svg>

JavaScript

var data = []

for (var i = 0; i < 5; i ++) {
  var d = {
    x:Math.random() * 380 + 10, 
    y: Math.random() * 280 + 10, 
    r: Math.random() * 20 + 10,
    label: Math.round(Math.random() * 100)
  }
  
  data.push(d);
}

function getMaxScale(bbox, radius) {
  var ratio = bbox.height / bbox.width;
  var maxHeight = radius * 2 * Math.cos(Math.PI/2 - Math.atan(ratio));
  return maxHeight / bbox.height;
}

var svg = d3.select("svg");

var circles = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
  .attr("cx", function(d) {return d.x})
  .attr("cy", function(d) {return d.y})
  .attr("r", function(d) {return d.r})
  .attr("fill", "none")
  .attr("stroke", "black");
  
var txt = svg.selectAll("text")
  .data(data)
  .enter()
  .append("text")
  .text(function(d) {return d.label})
  .attr("text-anchor", "middle")
  .attr("dy", "0.35em")
  .each(function(d, i) {
    var d3el = d3.select(this);
    var scale = getMaxScale(this.getBBox(), d.r);
    d3el.attr("transform", "translate(" + d.x + "," + d.y + ") scale(" + scale + ")");
  })