mcpeterson
mcpeterson

Reputation: 5134

Easily print a nicely looking tree diagram from data in R

I have a dataset like the following (this will be of arbitrary length, but with one count column at the end):

dd <- data.frame(
   "level1" = c("a", "a", "b"),
   "level2" = c("c", "d", "c"),
   "cnt" = c(1, 3, 5)
)

And I'd like to print out a nice looking tree of this structure, without a ton of work :). Already attempted just doing a sort, and looking at boundary conditions to output data.

Ideally the tree structure will look like this from the data above:

level1     level2
a: 4  ---> c: 1
      ---> d: 3
b: 5  ---> c: 5

Where the last vector of the dataframe gets summed up the distinct branches of the tree, but with nice diagrams for visualization. Last vector, because we can have an arbitrary number of levels. Does anyone know an easy path forward for this without writing out my own set of tree algorithms?

Image of graph: enter image description here

Upvotes: 3

Views: 580

Answers (1)

agstudy
agstudy

Reputation: 121568

Using igraph package for example, you can get with little work. I corrected some typo in your data and add a new edge to get prettier graph. My graph look like this one:

enter image description here

And here my R code:

 actors <- data.frame(name=c('a','b','c','d'))
relations <- data.frame(from=c("a", "a", "b",'c'),
                        to=c("c", "b", "c",'d'),
                        weight=c(1, 3, 5,4))
g <- graph.data.frame(relations, directed=TRUE, 
                      vertices=actors)

E(g)$label=E(g)$weight
E(g)$label.cex=3
plot(g,edge.width=E(g)$weight,layout=layout.fruchterman.reingold)

Upvotes: 1

Related Questions