How to Hide Legend in ggplot2 in R ?
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.
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.
theme (line, text, axis.title,legend.position)
- 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.