Open In App

How to Hide Legend in ggplot2 in R ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will discuss how can we hide a legend in R programming language, using ggplot2.

Note: Here, a line plot is used for illustration the same can be applied to any other plot.

Let us first draw a regular plot, with a legend, so that the difference is apparent. For this, firstly, import the required library and create dataframe, the dataframe should be such that it can be drawn on the basis of groups and is color differentiated because only then a legend will appear.

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 to hide the legend, theme() function is used after normally drawing the plot.

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 (line, text, axis.title,legend.position)

  • Parameter:
  • line: all line elements (element_line())
  • text: all text elements (element_text())
  • axis.title: labels of axes (element_text()). Specify all axes’ labels (axis.title)
  • legend.position: changes the legend position to some specified value.

To hide the legend this function is called with legend.position parameter, to which “none” is passed to not make ut appear on the plot.

Syntax: theme(legend.position=”none”)

Code:

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


Output:



Last Updated : 18 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads