How to change legend title in ggplot2 in R?
In this article, we will see how to change the legend title using ggplot2 in R Programming.
We will use ScatterPlot. For the Data of Scatter Plot, we will pick some 20 random values for the X and Y axis both using rnorm() function which can generate random normal values, and here we have one more parameter for naming the legend named ‘Users’. We use sample() function to generate data for Users vector. sample() function takes a sample of the specified size of elements with or without replacement. Then create a DataFrame and assign it to ‘data’ data object.
Now we will create a Plot using ggplot() function and make it Scattered using geom_point() function. Here for creating a simple Scatterplot, we use only the size argument of geom_point() function to set the size of the point.
Method 1: Change Legend Title using guides() Function.
Now if we want to change Legend Title then we have to add guides and guide_legend functions to the geom_point function. Inside guides() function, we take parameter named ‘color’ because we use color parameter for legend in ggplot() function. ‘color’ has call to guide_legend() guide function as value. Inside guide_legend() function, we take an argument called ‘title’ , which has the new title of legend as a value.
Syntax : guide_legend(title)
- title : A string, which is the New Title of ggplot2 Legend. if title has value NULL, the title is not shown.
Return : Legend Guides for various scales
Here title “Users” is replaced with “Users By guides” By using guides() function.
Method 2: Change Legend Title using labs() Function.
Generally labs() function is widely used for assigning title, subtitle, caption, and tags to plot, but it can also change the title of other aesthetics. Like here we have one extra aesthetic inside ggplot() function named ‘color’ for legend. So, we can also change the title of ‘color’ aesthetic (i.e. Legend) For that we have to add lab function to geom_point and assign the parameter ‘color’ to its function and give it the new title of ggplot2 plot Legend.
Syntax : labs(…)
- Generally labs() has many parameters like title, subtitle, caption, tags, label. we can use them as per our requirements. here we use only one plot aesthetic as a parameter which changes the title of plot Legend.
- … : List of new aesthetic pairs.
Return : Labels which useful to make plot more understandable.
Here title “Users” is replaced with “Users By labs” By using labs() function.