【问题标题】:Color nodes in rpart treerpart 树中的颜色节点
【发布时间】:2015-10-28 11:01:13
【问题描述】:

box.col() 着色如何用于 prp 树图?我想使用基于任何 3 个年龄类别或基于任何 3 个节点编号分组的三种颜色为终端节点着色(对于我的实际数据,两者一起增加,因此基于结果值或节点编号的着色将起作用)。

我已阅读包文档和小插图,但仍然不知道从哪里开始,即使只是针对两组。下面是我尝试控制 2 种颜色的两个示例。第一个看似随机,第二个虽然显然会根据拟合的节点值着色,但根本不输出任何颜色。

library(rpart)
library(rpart.plot)

data(ptitanic)

tree <- rpart(age ~ ., data = ptitanic)

prp(tree, extra = 1, faclen=0,  nn = T,
    box.col=c("green", "red")) #apparently random colouring?

prp(tree, extra = 1, faclen=0, nn = T,
    box.col=c("green", "red")[tree$frame$yval]) #no colour

【问题讨论】:

    标签: r plot rpart


    【解决方案1】:

    使用 box.palette 参数:

    library(rpart.plot)
    data(ptitanic)
    tree <- rpart(age ~ ., data = ptitanic)
    prp(tree, extra=1, faclen=0,  nn=T, box.palette=c("green", "red"))
    # examples using built-in palettes
    prp(tree, extra=1, faclen=0,  nn=T, box.palette="GnRd")
    prp(tree, extra=1, faclen=0,  nn=T, box.palette="Blues")
    

    box.palette 参数是在 rpart.plot 版本 2.0 中添加的,该版本在您的原始帖子之后发布。

    【讨论】:

      【解决方案2】:

      事实证明,指定条件 box.col 语句与指定语句以有条件地为其他图表着色并没有什么不同,我发现这篇文章对提出解决方案很有用:Using Conditional Statements to Change the Color of Data Points

      关键是tree$frame 提供了一个数据框,可用于帮助指定条件语句(请参阅rpart documentation)。 yval 变量保存感兴趣的预测结果(在本例中为年龄),可用于指示颜色。

      以下是2色和3色的配色方案:

      # 2 colours
      # use ifelse: if predicted age > 30 colour red, else colour green
      prp(tree, extra = 1, faclen=0, nn = T,
          box.col=ifelse(tree$frame$yval > 30, 'red', 'green')) 
      
      # 3 colours
      # use findInterval: if age [0,20) then green; if age [20,30) then orange, else red
      prp(tree, extra = 1, faclen=0, nn = T,
         box.col=c("green", "orange", "red")[findInterval(tree$frame$yval, v = c(0,20,30))])
      

      节点号未存储在 tree$frame 中,因此我不确定如何根据节点号为框着色,但出于我的目的,上述解决方案将起作用。

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 2020-10-03
        • 2019-01-15
        • 2019-10-31
        • 2011-07-03
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 2016-05-11
        相关资源
        最近更新 更多