首页 > 解决方案 > 通过颜色匹配节点列表为 rpart.plot 中的节点着色

问题描述

在函数 rpart.plot(来自 rpart.plot 包,扩展至 rpart 包)中有参数box.col,它控制树中节点的颜色。如何设置它以便它为节点着色,以便相同响应的节点着色相同?

我已经使用参数尝试了许多不同的变体box.col,例如使用colsas 因子,它忽略了选择的颜色。到目前为止我最接近的如下所示


set.seed(1);x <- runif(100)
set.seed(2);y <- runif(100)

data <- matrix(c(x,y),ncol=2)
fact <- as.numeric(factor(--((x > 0.5 & y < 0.5))))
fact[x < 0.1] = 3
cols <- (c("grey80", "red", "blue"))


plot(data, col=fact)

t1 <- rpart(factor(fact) ~ data)
rpart.plot(t1, type=5, extra=2,
           box.col=cols)

示例失败的情节 我希望/希望每个匹配的响应节点的颜色相同。在给定的代码中,我希望“1”节点为灰色 80,“2”为红色,“3”为蓝色。上图显示了实际发生的情况,这没有帮助。

如第一部分所述,我如何设置它以便它为节点着色,以便相同响应的节点着色相同?

标签: rrpart

解决方案


如何使用box.pallete属性

rpart.plot(t1, type=5, extra=2,
           box.palette = list('grey80','red','blue'))

在此处输入图像描述

如需更多说明,如果您将 cols 设置为factorin rpart.plot,则 cols 将按顺序分配给每个节点。

例如,

>t1

1) root 100 29 1 (0.7100000 0.2200000 0.0700000)  # --> 'grey80'
   2) data1>=0.1037049 93 22 1 (0.7634409 0.2365591 0.0000000)  # --> 'red'
     4) data1< 0.5413779 47  0 1 (1.0000000 0.0000000 0.0000000) * # --> 'blue'
     5) data1>=0.5413779 46 22 1 (0.5217391 0.4782609 0.0000000)  # --> 'grey80'
      10) data2>=0.4849942 24  0 1 (1.0000000 0.0000000 0.0000000) * # --> 'red'
      11) data2< 0.4849942 22  0 2 (0.0000000 1.0000000 0.0000000) *# --> 'blue'
   3) data1< 0.1037049 7  0 3 (0.0000000 0.0000000 1.0000000) * # --> 'grey 80'

推荐阅读