D3 Tree Graph - Text Center, Controlling Height, a

2019-05-31 09:24发布

I am working on a D3 Tree Graph with this fiddle: http://jsfiddle.net/q1a6o1o8/2/

I am having some issues with the following:

  1. I can't seem to properly center the text inside the rectangle nodes. I haven't had a problem when using circles. "text-anchor" "middle' isn't working. I'm trying to avoid using the "x" attribute to center so that the text is always centered inside the "rect" regardless of its length.

  2. Is there a way to make the rectangles responsive so that basically the width or height of the rectangle changes based on the length of the text included? i.e. longer text should stay centered inside the "rect" node

  3. I've added Arrow icons on the links but I am getting weird behavior in regards to having them appear. If you click around on the fiddle you'll see the arrows will appear in some cases but not appear in others?

  4. How can I adjust the distance between each node up and down (not depth). Reason I ask is when I expand the graph all the way out, the leaf nodes seem to be overlapping each other. When I increase the height of the svg container to 900 that seems to help but the other nodes are expanded too far away from each other earlier in the graph. Is there a way to keep the parent nodes closer together but keep the leaf nodes from overlapping without increasing the SVG height?

    var height = 900; //changed from 650
    

Thanks

1条回答
【Aperson】
2楼-- · 2019-05-31 09:52

1: Since text-anchor is a style, you have to use the following:

nodeEnter.append("text").style("text-anchor", "middle")

You'll notice that this will set the text to be centered on the left edge of the rect. You can fix this by offsetting either the text or the rect element by half the width of the rect.

2: This too is fairly simple. After drawing the text elements you would want to run through them (each function), select their respective rect (should be possible using the d parameter), and then set the width of the rect to be the calculated width.

svg.selectAll("text").each(function (d){
var textWidth = this.getBBox().width;
});

3: Move .attr("marker-end", "url(#arrowhead)") to the end of link.enter().append("line") (after you set y2).

4: The easiest way is to increase the tree height, such as var tree = d3.layout.tree().size([1500, width]); and then enable zooming and dragging (example). You could theoretically customize the depth spacing, but it would likely be more work than zoom/drag. Another option is to add .nodeSize([50,return 50;}]) to var tree = ..., but this changes the spacing for all nodes regardless of depth. Note that setting nodeSize overrides size and causes the tree to automatically change size based on the number of nodes.

查看更多
登录 后发表回答