使用R演示带有拆分的决策树

使用R演示带有拆分的决策树,r,igraph,decision-tree,R,Igraph,Decision Tree,我在网上找到了一个我正试图在R中复制的图形。我已经成功地创建了下面图像的第一个图形,现在我正在尝试构建决策树。它仅用于说明目的,因此不会构成某些模型的一部分 生成第一个绘图的代码: x1 <- sample(c(1:100), 100, replace = TRUE) x2 <- sample(c(1:100), 100, replace = TRUE) d <- data.frame(x1, x2) d %>% mutate( colours = c

我在网上找到了一个我正试图在R中复制的图形。我已经成功地创建了下面图像的第一个图形,现在我正在尝试构建决策树。它仅用于说明目的,因此不会构成某些模型的一部分

生成第一个绘图的代码:

x1 <- sample(c(1:100), 100, replace = TRUE)
x2 <- sample(c(1:100), 100, replace = TRUE)

d <- data.frame(x1, x2)

d %>% 
  mutate(
    colours = case_when(
      x1 < 50 & x2 >= 60 ~ "green",
      x1 >= 50 & x2 >= 60 ~ "red",
      x1 < 70 & x2 < 60 ~ "red",
      x1 >= 70 & x2 < 20 ~ "red",
      x1 > 70 & x2 > 20 ~ "green"
    )
  ) %>% 
  ggplot(aes(x = x1, y = x2)) +
  geom_point(aes( color = colours)) +
  geom_line(data = data.frame(x = c(1, 100), y = c(60, 60)), aes(x = x , y = y), linetype = "dashed") +
  annotate("text", label = "Split 1", x = 105, y = 60) +
  geom_line(data = data.frame(x = c(50, 50), y = c(60, 100)), aes(x = x, y = y), linetype = "dashed") +
  annotate("text", label = "Split 2", x = 50, y = 101) +
  geom_line(data = data.frame(x = c(70, 70), y = c(1, 60)), aes(x = x, y = y), linetype = "dashed") +
  annotate("text", label = "Split 3", x = 70, y = 61) +
  geom_line(data = data.frame(x = c(70, 100), y = c(20, 20)), aes(x = x, y = y), linetype = "dashed") +
  annotate("text", label = "Split 4", x = 105, y = 20)
x1=50&x2>=60~“红色”,
x1<70和x2<60~“红色”,
x1>=70&x2<20~“红色”,
x1>70和x2>20~“绿色”
)
) %>% 
ggplot(aes(x=x1,y=x2))+
几何点(aes(颜色=颜色))+
几何图形线(data=data.frame(x=c(1100),y=c(60,60)),aes(x=x,y=y),线型=“虚线”)+
注释(“文本”,标签=“拆分1”,x=105,y=60)+
几何图形线(data=data.frame(x=c(50,50),y=c(60,100)),aes(x=x,y=y),线型=“虚线”)+
注释(“文本”,标签=“拆分2”,x=50,y=101)+
几何图形线(数据=数据帧(x=c(70,70),y=c(1,60)),aes(x=x,y=y),线型=“虚线”)+
注释(“文本”,标签=“拆分3”,x=70,y=61)+
几何图形线(data=data.frame(x=c(70100),y=c(20,20)),aes(x=x,y=y),线型=“虚线”)+
注释(“文本”,标签=“拆分4”,x=105,y=20)
其中:


现在如何创建决策树部件?我正在研究
igraph
包,但不知道在生成决策树模型时从何处开始。

也许您的问题更多的是关于如何使用
ggplot2
创建树。但是如果您只想可视化决策树模型,
rpart
rpart.plot
是一个很好的解决方案

library(rpart)
library(rpart.plot)
# Create model
tree <- rpart(mpg~., data=mtcars, cp=.05)
# Visualize Tree
rpart.plot(tree, box.palette=c("green","red","blue"), shadow.col="gray", nn=TRUE)
库(rpart)
库(rpart.plot)
#创建模型
树请参阅,以获取
ggparty
软件包的渐晕图,该软件包从安装了
partykit
软件包的树中绘制ggplot图形。