How to use scale_color_discrete() In R Language

scale_color_discrete() function deals with legend aesthetics. To remove the title, its name attribute is set to nothing or left black, which makes it not appear in the final plot. 

Syntax: scale_color_discrete(name)

Example: Remove legend title using scale_color_discrete().

R




library("ggplot2")
  
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
  
df=data.frame(x=-2:2,
              values=c(function1(-2:2),
                       function2(-2:2),
                       function3(-2:2),
                       function4(-2:2)),
              fun=rep(c("function1","function2",
                        "function3","function4"))
)
  
ggplot(df,aes(x,values,col=fun))+geom_line()
+scale_color_discrete(name="")


Output:

How to remove legend title in R with ggplot2 ?

At times, the legend keys are enough to display what they are supposed to describe. Thus, in such cases, the legend title can be dropped. In this article, we will discuss how the legend title can be removed using ggplot2 in the R programming language.

Let us first draw a regular plot with a legend title:

R




library("ggplot2")
  
function1<- function(x){x**2}
function2<-function(x){x**3}
function3<-function(x){x/2}
function4<-function(x){2*(x**3)+(x**2)-(x/2)}
  
df=data.frame(x=-2:2,
              values=c(function1(-2:2),
                       function2(-2:2),
                       function3(-2:2),
                       function4(-2:2)),
              fun=rep(c("function1","function2",
                        "function3","function4"))
)
  
ggplot(df, aes(x, values, col = fun)) + geom_line()


Output:

Similar Reads

Method 1: Using scale_color_discrete()

...

Method 2: Using theme()

scale_color_discrete() function deals with legend aesthetics. To remove the title, its name attribute is set to nothing or left black, which makes it not appear in the final plot....