Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily print a nicely looking tree diagram from data in R

Tags:

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

like image 272
mcpeterson Avatar asked Jan 23 '26 02:01

mcpeterson


1 Answers

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)
like image 172
agstudy Avatar answered Jan 25 '26 17:01

agstudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!