Skip to content
Related Articles

Related Articles

Improve Article

Remove Legend in ggplot2 in R

  • Last Updated : 14 Sep, 2021
Geek Week

In this article, we will discuss how to remove a legend from a plot using an R programming language.

Let us first look at the initial plot so the difference is apparent:

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:



Method 1: Using theme()

theme() function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look.

Syntax: theme (legend.position)

Parameter:

  • legend.position: changes the legend position to some specified value.

Calling theme function with legend.position set to none will get the job done.

Example: Removing legend

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()+
theme(legend.position="none")

Output:

Method 2: Using guides()

Another alternative is to call guides() method with an appropriate term that has been used to set the color difference for the plot objects produced. Either fill or color, it should be set to none.

Syntax: guides(color/fill=”none”) 

Example: Removing legend

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()
+guides(col="none")

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :