在R中随机森林图的图例

5

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

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

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

plot(model, log="y")

这给我下面的图表: enter image description here

我的问题是如何在此添加图例,以便我可以看到分类中每个值所对应的颜色?因为分类变量是data$classification。我无法弄清楚如何使用legend()函数来实现这一点。
2个回答

10

plot S3方法使用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)

enter image description here


1
我意识到这比我预期的要容易。我还在逐渐适应在R中绘图。我认为下面的代码也是正确的:legend("topright", legend=unique(train$classification), col=unique(as.numeric(train$classification)), pch=19) - seawolf
如何将“mar”参数重置为正确的值? - EngrStudent
1
@EngrStudent par(mar=c(1,1)) -> @EngrStudent par(mar=c(1,1)) - agstudy
有人知道是否有使用ggplot的示例吗? - Bear

0

你可以使用这个,

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接