【问题标题】:Legend for Random Forest Plot in RR中随机森林图的图例
【发布时间】:2013-12-18 04:05:13
【问题描述】:

我在 R 中使用 randomForest 函数创建了一个随机森林预测模型:

model = randomForest(classification ~., data=train, ntree=100, proximity=T)

接下来我绘制模型以查看模型的整体误差:

plot(model, log="y")

这给了我以下情节:

我的问题是如何在上面加上一个图例,以便我可以看到哪种颜色对应于用于分类的因子中的每个值?因子变量是data$classification。我不知道 legend() 调用来做到这一点。

【问题讨论】:

    标签: r plot random-forest


    【解决方案1】:

    plot S3方法plot使用matplot绘制随机森林模型。您应该手动添加图例。这应该是一个好的开始:

    library(randomForest)
    model = randomForest(Species ~., data=iris, ntree=100, proximity=T)
    layout(matrix(c(1,2),nrow=1),
           width=c(4,1)) 
    par(mar=c(5,4,4,0)) #No margin on the right side
    plot(model, log="y")
    par(mar=c(5,0,4,2)) #No margin on the left side
    plot(c(0,1),type="n", axes=F, xlab="", ylab="")
    legend("top", colnames(model$err.rate),col=1:4,cex=0.8,fill=1:4)
    

    【讨论】:

    • 我意识到这比我预期的要容易。我仍然习惯于在 R 中绘图。我认为这也可以正常工作:legend("topright", legend=unique(train$classification), col=unique(as.numeric(train$classification)), pch=19)
    • 如何将“mar”参数重置为正确的值?
    • @EngrStudent par(mar=c(1,1))
    • 有谁知道是否有这样的例子,但使用 ggplot 代替?
    【解决方案2】:

    你可以用这个,

    model$finalModel.legend <- if (is.null(model$finalModel$test$err.rate)) {colnames(model$finalModel$err.rate)} else {colnames(model$finalModel$test$err.rate)}
    legend("top", cex =0.7, legend=model$finalModel.legend, lty=c(1,2,3), col=c(1,2,3), horiz=T)
    

    【讨论】:

      猜你喜欢
      • 2017-01-12
      • 2016-11-10
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 2019-05-04
      • 2011-11-28
      • 2018-01-18
      • 2015-10-19
      相关资源
      最近更新 更多