Change the name of the legend ggplot

So this is my code for my ggplot. How is it easier for me to change the name of the legend? I know that I can just change my gg_group variable to my_title <- c(rep("train",10), rep("validation", 10)) . But I want to just change the title to " whatever I want " without changing any variables.

 library(ggplot2) y <- c(rnorm(10,1), rnorm(10,3)) x <- rep(seq(1,10,1),2) gg_group <- c(rep("train",10), rep("validation", 10)) gg_data <- data.frame(y=y, x=x, gg_group=gg_group) p <- ggplot(gg_data, aes(x=x, y=y, group=gg_group)) p + geom_line(aes(colour=gg_group)) 

I also tried this code:

p + geom_line(aes(colour=gg_group)) + scale_shape_discrete(name="Dataset",labels=c("Train", "Validation"))

But that does not work. * Edit, check out the excellent snwer from Jaap and JasonAizkalns.

+5
source share
2 answers

The reason it doesn't work is because you didn't use shape in ggplot code. Instead, you should use scale_color_discrete as follows:

 scale_color_discrete("Dataset") 
+1
source

@Jaap is correct. If you use scale_color_discrete you can change the name of the legend with the name, and you should not pass any arguments to labels as they will be considered, names defined in colour aesthetics. This takes into account the differences between:

 p + geom_line(aes(colour = gg_group)) + scale_color_discrete(name = "Dataset") 

and

 p + geom_line(aes(colour = gg_group)) + scale_color_discrete(name = "Dataset", labels = c("New Label 01", "New Label 02")) 
+5
source

Source: https://habr.com/ru/post/1234721/


All Articles