r - 使用朝阳 View 绘制 rpart 决策树模型

标签 r sunburst-diagram

我找到了一种使用 sunburstR 包从 rpart 绘制决策树解决方案的方法。要绘制旭日形图,必须有代表序列的 data.frame。我将决策树结果修改为如下序列

决策树的结果

rpart(Species~.,data=iris)

n= 150 

node), split, n, loss, yval, (yprob)
      * denotes terminal node

1) root 150 100 setosa (0.33333333 0.33333333 0.33333333)  
  2) Petal.Length< 2.45 50   0 setosa (1.00000000 0.00000000 0.00000000) *
  3) Petal.Length>=2.45 100  50 versicolor (0.00000000 0.50000000 0.50000000)  
    6) Petal.Width< 1.75 54   5 versicolor (0.00000000 0.90740741 0.09259259) *
    7) Petal.Width>=1.75 46   1 virginica (0.00000000 0.02173913 0.97826087) * 

旭日序列:

sequences_1<-1
sequences_1<-data.frame(sequences_1)
sequences_1[1:3,]<-1
sequences_1$V1[1]<-"Petal.Length<_2.45-setosa"
sequences_1$V1[2]<-"Petal.Length>=2.45-Petal.Width<_1.75_54_5-versicolor"
sequences_1$V1[3]<-"Petal.Length>=2.45-Petal.Width>=1.75_46_1-virginica"
sequences_1$V2[1]<-50
sequences_1$V2[2]<-54
sequences_1$V2[3]<-46
sequences_1$sequences_1<-NULL

绘制旭日图:

library(sunburstR)
sunburst(sequences_1,count=TRUE)

旭日图的序列,我手动完成的。有人知道如何从 rpart 决策树的结果中像上面那样自动构建序列吗?

最佳答案

d3r提供函数 d3_partyrpart/partykit 转换为 d3 层次结构。 sunburst 可以使用 d3_party 的结果,稍作修改即可将 “rule” 更改为 “name”。这并不理想,但在大多数情况下都能完美运行。

library(rpart)
library(d3r)
# d3_party requires partykit
# install.packages("partykit")
library(sunburstR)

rp <- rpart(Species~.,data=iris)
rp_d3 <- d3_party(rp)

# one trick/hack required since sunburst expects
#   name but d3_party gives rule
#   this is ugly but let's replace all "rule" with "name"
#   with gsub
rp_d3 <- gsub(
  x = rp_d3,
  pattern = '"rule":',
  replacement = '"name":'
)

sunburst(
  rp_d3,
  valueField = "n",
  sumNodes = FALSE,
  count = TRUE,
  legend = FALSE
)

关于r - 使用朝阳 View 绘制 rpart 决策树模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272101/

相关文章:

r - PieDonut 不显示某些饼图标签

javascript - 向 d3 sunburst 添加标签

r - 跟进: How to make a sunburst plot in R?

R:单文件 Shiny 应用程序的显示模式

command-line - R 中的命令行问题

R:用向量中的项替换NA

python - Plotly:后续如何使用 graph_objects 创建旭日子图?

r - 使用 data.table 将 lm 函数应用于不同范围的数据和单独的组

r - 为什么 1..99,999 == "1"。 R 中的 ."99,999",但 100,000 != "100,000"?