Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change ggplot legend title

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.

like image 617
TKN Avatar asked Oct 28 '15 17:10

TKN


People also ask

How do you change the legend title in Ggplot?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change my legend title?

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.

How do you change the legend in R?

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.

How do I create a legend in ggplot2?

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.


2 Answers

@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"))
like image 146
JasonAizkalns Avatar answered Sep 21 '22 13:09

JasonAizkalns


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")
like image 21
Jaap Avatar answered Sep 21 '22 13:09

Jaap