rd3tree

Display uneven Trees with d3tree


I have the following data that I read from csv file:

Level1,Level2,Level3,value
1,1.1,1.1.1,1.0
1,1.2,,1.1
1,1.3,1.3.1,1.0
2,2.1,,1.1
2,2.2,2.2.1,1.5
3,3.1,3.1.1,1.2
3,3.1,3.1.2,1.4

As you can see my tree depth varies for different branches. I use the code below to display the tree in R.

require(d3Tree)
TN<-as.data.frame(read.csv("nodes.csv",header=TRUE,sep=",")) 
TNjson<-df2tree(rootname="root",TN,toolTip = TN$value)
d3tree(list(root=TNjson,layout="cartesian"))

The output displays as below. My question is how do I display this tree as intended, without empty leafs?

d3Tree Output


Solution

  • Just make NAs the empty strings when you read your file:

    TN<-read.csv("nodes.csv", na.strings="")
    

    No need to coerce to a data.frame, since read.csv already returns a data.frame and no need also to specify the header and the sep, which are the correct ones by default. On the other hand, you need to specify the values you want to be translated to NAs when reading the file, and in this case it's the empty string.