So this is my code for my ggplot. How do I easiest change the title 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 change 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 have also tried this code:
p + geom_line(aes(colour=gg_group)) +
scale_shape_discrete(name="Dataset",labels=c("Train", "Validation"))
But this does not work. *Edit, check great snwer from Jaap and JasonAizkalns.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
Change the legend name using select dataSelect your chart in Excel, and click Design > Select Data. Click on the legend name you want to change in the Select Data Source dialog box, and click Edit. Note: You can update Legend Entries and Axis Label names from this view, and multiple Edit options might be available.
In order to change the legend size in R you can make use of the cex argument. Values bigger than 1 will lead to a bigger legend and smaller to smaller legends than the default.
Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.
@Jaap is correct. If you use scale_color_discrete
you can change the name of the legend with name and you do not have to pass any arguments to labels
as they will assume the names defined in your colour
aesthetic. That is consider 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"))
The reason it is not working is because you did not use a shape
in your ggplot
code. Instead you should use scale_color_discrete
as follows:
scale_color_discrete("Dataset")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With