简体   繁体   中英

Text not displaying in the middle of circles in d3js

The following code packs circles in d3js.

 csjson = { "children": [{ "name": "DirtySprite", "count": 8833 }, { "name": "LineSprite", "count": 1732 }] }; var diameter = 200; var pack = d3.layout.pack().size([diameter - 4, diameter - 4]).padding(2).sort(function(a, b) { return Math.random(); }).value(function(d) { return d.count; }); var svg = d3.select("body").append("svg").attr("width", diameter).attr("height", diameter); var vis = svg.datum((csjson)).selectAll(".node").data(pack.nodes).enter().append("g"); var titles = vis.append("title") .attr("x", function(d) { return dx; }).attr("y", function(d) { return dy; }).text(function(d) { return d.children ? "" : (d.name + ' ' + d.count); }); var circles = vis.append("circle") .attr("stroke", "black") .style("fill", function(d) { return !d.children ? "tan" : "beige"; }) .attr("cx", function(d) { return dx; }) .attr("cy", function(d) { return dy; }) .attr("r", function(d) { return dr; }); var textLabels = vis.filter(function(d) { return !d.children; }).append("text").style("text-anchor", "middle") .text(function(d) { return d.name.substring(0, dr / 3); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <body> </body> 

The circles form correctly however the labels are displaying on the upper-left corner of the screen rather than in the center of the circles.

var textLabels = vis.filter(function(d) {
    return !d.children;
}).append("text").style("text-anchor", "middle")
  .text(function(d) {
    return d.name.substring(0, d.r / 3);
});

How to display the text in the middle of the circles?

The problem is because you are not setting the x and y value to the text DOM.

Instead of this:

var textLabels = vis.filter(function(d) {
    return !d.children;
}).append("text").style("text-anchor", "middle")
  .text(function(d) {
    return d.name.substring(0, d.r / 3);
});

It has to be

var textLabels = vis.filter(function(d) {
    return !d.children;
  }).append("text").style("text-anchor", "middle") .attr("x", function(d) {
    return d.x;
  }).attr("y", function(d) {
    return d.y;
  })
  .text(function(d) {
    return d.name.substring(0, d.r / 3);
  });

working fiddle here

You have to set the x and y position to the texts:

var textLabels = vis.filter(function(d) {
    return !d.children;
}).append("text").style("text-anchor", "middle")
.attr("x", function(d) {
    return d.x;
}).attr("y", function(d) {
    return d.y;
}).text(function(d) {
    return d.name.substring(0, d.r / 3);
});

This is just the generally principle, you may need to adjust x and y according to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM