0

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")
user1491868
  • 596
  • 4
  • 15
  • 42
  • 1
    If you look when you run your code it returns an error message `Theme element legend.title must be an object of type element_text`, however you don't set custom legend titles with this function anyways. As caret uses shape and colour scales to differentiate algorithms you can use `guides(shape = guide_legend(title="Splitting algo"), colour = guide_legend(title="Splitting algo"))` instead of what you have in `theme()`. – Nautica Feb 04 '21 at 00:06

1 Answers1

1

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213