Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot tree in ggplot in R

Tags:

r

tree

ggplot2

I wonder if it is possible to plot tree by ggplot? let's say:

library(rpart
library(rpart.plot)

data(iris)
mod <- rpart(Species~., data=iris)
prp(mod)

enter image description here

Can I plot similar graph in ggplot?

like image 552
Cina Avatar asked Jun 27 '15 09:06

Cina


People also ask

How do you plot a tree model in R?

In machine learning, a decision tree is a type of model that uses a set of predictor variables to build a decision tree that predicts the value of a response variable. The easiest way to plot a decision tree in R is to use the prp() function from the rpart. plot package.

How do you visualize a phylogenetic tree in R?

After you've loaded your tree in R, visualization is really simple. The ggtree function directly plots a tree and support several layouts, such as rectangular, circular, slanted, cladogram, time-scaled, etc. Add a tree scale. You can easily turn your tree into a cladogram with the branch.

How do I plot a curve in ggplot?

In order to create a normal curve, we create a ggplot base layer that has an x-axis range from -4 to 4 (or whatever range you want!), and assign the x-value aesthetic to this range ( aes(x = x) ). We then add the stat_function option and add dnorm to the function argument to make it a normal curve.

Does ggplot only work with Dataframe?

ggplot only works with data frames, so we need to convert this matrix into data frame form, with one measurement in each row. We can convert to this “long” form with the melt function in the library reshape2 .


2 Answers

The autoplot.rpart() function in the survMisc package could get you part of the way there. But you'd likely need to clean up the presentation of the the plot, potentially layering in symbols, etc. It seems to be just a starting point:

library(rpart)
library(survMisc)

data(iris)
mod <- rpart(Species~., data=iris)

autoplot(mod, branch=0)

ggplot2 rpart fit

like image 100
Forrest R. Stevens Avatar answered Oct 10 '22 20:10

Forrest R. Stevens


You can use rattle, which produces nice rpart plots

library(rattle)

fancyRpartPlot(rpart(Species~., data=iris),yesno=2,split.col="black",nn.col="black", 
               caption="",palette="Set2",branch.col="black")

Link to my plots

like image 38
Cateded Ur Avatar answered Oct 10 '22 18:10

Cateded Ur