Search code examples
rggplot2r-caretr-ranger

R caret random forests ggplot modify legend


How do I modify the default plot legend produced by applying ggplot to a caret object built using the ranger algorithm? For example, suppose I would like the legend title to be, "Splitting algo" instead of the default, "Splitting Rule."

library(caret)

trainIndex <- createDataPartition(iris$Species, p = 0.80, list = FALSE)

train <- iris[ trainIndex,]

test  <- iris[-trainIndex,]

rfs <- train(Species ~ ., data = train, trControl = trainControl(method = "cv", number = 10), method = "ranger", tuneGrid = expand.grid(mtry = seq(1, 3, 1), splitrule = c("gini", "extratrees"), min.node.size = 1))

ggplot(rfs) + 
  xlab("Number of parameters") +
  ylab("Accuracy") +
  theme(legend.title = "Splitting algo")

Solution

  • You set name of legend using scale_color_discrete and scale_shape_discrete.

    library(ggplot2)
    
    ggplot(rfs) + 
      xlab("Number of parameters") +
      ylab("Accuracy") +
      scale_color_discrete(name = "Splitting algo")  +
      scale_shape_discrete(name = "Splitting algo")
    

    enter image description here