D3 radial tidy tree nodes

Greetings to all!

I recently found the beautiful notebook by Mike Bostock and forked it for using it as a template for genealogy.

Currently I am struggling with editing the nodes. I would like to insert line breaks to create something like the following:

data ={“name”=“firstname lastname \n
born xx.xx.xxxx in somecity \n
married yy.yy.yyyy in somewhere \n
died xx.xx.xxxx in samecity \n
some_additional_information”
}

Thank you in advance for some guidance :slight_smile:

edit: OK, I was clearly not awake when I first replied. Sorry, let me try again!

To get “line breaks” in a text element of an SVG, you’ll need to break up the text into multiple <tspan>s. Here’s a blog post by Jarrett Meyer that describes one way to accomplish this.

Here’s my suggestion for how to adapt your notebook.

In your data cell, for the nodes of the tree where you’d like text elements with multiple lines, put in your strings with linebreaks like this:

{"name": `firstname lastname
born xx.xx.xxxx in somecity
married yy.yy.yyyy in somewhere
died xx.xx.xxxx in samecity
some_additional_information` }

Now, replace the node.append("text") statement in the chart cell with this:

  node.append("text")
      .attr("dy", "0.31em")
      .attr("x", d => d.x < Math.PI === !d.children ? 6 : -6)
      .attr("text-anchor", d => d.x < Math.PI === !d.children ? "start" : "end")
      .attr("transform", d => d.x >= Math.PI ? "rotate(180)" : null)
    .selectAll('tspan')
    .data(d => d.data.name && d.data.name.split("\n"))
    .enter()
    .append("tspan")
    .attr("class", "text")
    .text(d => d || '')
    .attr("x", 6)
    .attr("y", (d,i,n) => 6*(i - (n.length-1)/2))
  .clone(true).lower()
      .attr("stroke", "white");

This is very rough – you will probably have to play around more with the x and y attributes of the tspan to get the positioning / spacing right. And you’ll probably also have to adjust the font size to keep multiple elements from overlapping.

Here’s a quick fork – you can see that the parameters aren’t quite right yet:

2 Likes

Thank you so much! This is exactly what I was looking for. :smiley:

Adjusting the parameters also depends on how much information will be available. Especially the later generations usually don’t provide much information.

1 Like