简体   繁体   中英

Appending text to D3 force layout graph

I'm trying to modify the force layout graph here http://bl.ocks.org/mbostock/4062045 by appending text within the circles, but the text doesn't appear. I added this block of code to the original code on the site.

node.append("text")
  .style("text-anchor", "middle")
  .text(function(d) { return d.name; }); 

I don't have your code in entirety, but I think you are adding text INTO circles, and since circles are small, you don't see the text.

Now, your nodes are currently circles (I just suppose). If you want both circles and text for each node, your nodes should be svg g elements (g stands for "group"), and to each such g element you assign a circle and a text. More about that you can find here (code is included there too)

EDIT: Once you see labels, you will like to position them in a nice way in relation to nodes. Here is an almost official recommendation related to positioning labels to the nodes of a graph:

For vertical alignment, use the "dy" attribute:

by default, the baseline of the text is at the origin (bottom-aligned)
a dy of .35em centers the text vertically
a dy of .72em places the topline of the text at the origin (top-aligned)

Using em units is nice because it will scale automatically based on the font size. If you don't specify units, it defaults to pixels.

For horizontal alignment, use the "text-anchor" attribute:

the default is "start" (left-aligned for left-to-right languages)
"middle"
"end"

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