Change Display Order of ggplot2 Plot Legend in R
In this article, we will see how to change display order of ggplot2 legend in R Programming Language.
For that, first we should load ggplot2 package using library() function. Syntax for loading or installing ggplot2 package is give below. to install ggplot2 package, write following command to R Console.
To Create a plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function.
Changing the order of Legend to Desired Order :
Now for Changing the order of Legend, we have to create new dataframe, let us say newDF. Here we will copy old DataFrame (DF) to new dataframe (newDF) bacause we only want to change the order of legend. To copy DF to newDF, we simply assign DF to newDF.
newDF <- DF
For changing the order of wsers, we will use factor() function and inside factor we will use levels parameter to assign the new order of Legend.
Syntax : factor(x, levels)
- x : A Data Object, which takes distinct values. here we want to change only Users column of dataframe. for that we will use newDF$Users as a first parameter (i.e. inplace of x)of factor
- levels : A Character string or column that determines the new order of x vector
Return : Encode a vector as a Factor.
newDF$Users <- factor(newDF$Users, levels = c(“User4”, “User1”, “User5”, “User2”, “User3”))
Now, we will simply create a ScatterPlot with this New DataFrame using as always ggplot() and geom_point() function.
Reversing the Order of Legend
For Reversing the order of legend, we simply use rev() function as a value of levels parameter of factor function and inside rev() function, we assign the order of values that we want to reverse.
Syntax : rev(x)
- x : rev function has only one parameter, which represents the vector or other Data Object that we want to reverse its order, DF$Users in our example.
Return : Reversed order of its argument.
newDF$Users <- factor(newDF$Users, levels = rev(DF$Users))