Stophface Stophface - 1 year ago 153
R Question

Plot legend random Forest r

I run the

algorithm in
and want to plot the
OOB Error
with a legend describing it. However, I cannot seem to get it right.

That is the way it looks:

messed up plot

Thats the code I used:

plot(rfOutput, log = "y", type = "l")
legend("top", colnames(rfOutput$err.rate),col=1:6,cex=0.8,fill=1:6)

How would I specify the colors used for the lines as well as the linetype? I dont want it dashed. Furthermore, how would I add the matching legend?

jav jav
Answer Source

Here's a solution where you extract the plot data from plot(rfOutput...) and re-plot it using the ggplot package:


# Use random forest example from randomForest package
rfOutput <- randomForest(Species ~ ., data=iris, importance=TRUE, ntree = 6, proximity=TRUE)

# Get OOB data from plot and coerce to data.table
oobData =

# Define trees as 1:ntree
oobData[, trees := .I]

# Cast to long format
oobData2 = melt(oobData, id.vars = "trees")
setnames(oobData2, "value", "error")

# Plot using ggplot
ggplot(data = oobData2, aes(x = trees, y = error, color = variable)) + geom_line()

The output is as follows:

enter image description here