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)
Can I plot similar graph in ggplot?
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.
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.
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.
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 .
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With