Reversing the order of a ggplot2 legend
In this article, we will see how to Reverse the order of Legend Items of ggplot2 plots in the R programming language.
First, load the ggplot2 package by using the library() function. If you have not installed it yet, you can simply install it by writing the below command in R Console.
Let us first create a regular plot, so that the difference is apparent.
To Reverse the order of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take the parameter color, which will call guide_legend() guide function as value. Inside guide_legend() function, we take an argument called reverse, which is a logical parameter. If “reverse = TRUE”, the order of legends is reversed otherwise it will remain as it was.
Syntax : guides(…)
- … : either a string or call to a guide function. here we call guide_legend() guide function.
Return : each scale can be set scale-by-scale
Syntax : guide_legend(reverse = TRUE)
- reverse : It is a logical parameter that specify the order of plot legend.
Return : Legend Guides for various scales