Skip to content
Related Articles

Related Articles

Improve Article

How to change legend title in R using ggplot ?

  • Last Updated : 30 May, 2021

A legend helps understand what the different plots on the same graph indicate. They basically provide labels or names for useful data depicted by graphs. In this article, we will discuss how legend names can be changed in R Programming Language.

Let us first see what legend title appears by default.

Example:

R




library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()

Output:



Now let us discuss various ways in which a legend title can be provided. 

Method 1: Using scale_colour_discrete()

To change the legend title using this method, simply provide the required title as the value to its name attribute.

Syntax:

scale_colour_discrete(name=”value”)

Example:

R




library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
scale_colour_discrete(name="participant")

Output:



Method 2: Using labs()

Labs() function is used to modify axis, labels, etc. It can be used to change the legend title by providing the appropriate title name to col attribute.

Syntax:

labs(cols=”value”)

Example:

R




library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
labs(col="participant")

Output:

Method 3: Using guides()

guides() can be used to alter legend title. To change the title with this function pass the required name to as an argument to guide_legend() function and this ultimately as the value to the attribute col.

Syntax:

guides(col=guide_legend(“value))

Example:

R




library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
guides(col=guide_legend("participant"))

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :