简体   繁体   English

R中随机森林地块的图例

[英]Legend for Random Forest Plot in R

I have created a random forest prediction model in R using the randomForest function: 我使用randomForest函数在R中创建了一个随机森林预测模型:

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

Next I plotted the model in order to see the overall error of the model: 接下来,我绘制模型以查看模型的整体错误:

plot(model, log="y")

This gives me the following plot: 这给了我以下情节: 在此输入图像描述

My question is how do I put a legend on this so that I can see which color corresponds to each value in the factor used for the classification? 我的问题是如何在这上面添加一个图例,以便我可以看到哪个颜色对应于用于分类的因子中的每个值? The factor variable is data$classification . 因子变量是data$classification I can't figure out the legend() call to do this. 我无法弄清楚要做到这一点的legend()调用。

The plot S3 method plot use matplot to plot random forest model. 图S3方法图使用matplot绘制随机森林模型。 You should add legend manually. 您应该手动添加图例。 This should be a good start: 这应该是一个好的开始:

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)

在此输入图像描述

you can use this, 你可以用这个,

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM