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)

Parameter :

  • 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))

R




# Load Package
library("ggplot2")
 
# Create a DataFrame
DF <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015),                       
                 Points = c(30, 20, 15, 35, 50),
                 Users = c("User1", "User2", "User3", "User4", "User5"))
 
# Copy Old dataframe to New DataFrame.
newDF <- DF
 
# Reverse the order of Users column of DataFrame
newDF$Users <- factor(newDF$Users,
                      levels = rev(DF$Users))
 
# Create ScatterPlot with new dataframe.
ggplot(newDF,aes(Year, Points, color = Users))+
  geom_point(size = 10)


Output:
 

Scatter Plot with Reversed Order of ggplot2 Legend



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 given below. to install ggplot2 package, write following command to R Console.

install.packages("ggplot2")
library("ggplot2")

To Create a plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function.

R




# Load Package
library("ggplot2")
 
# Create a DataFrame
DF <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015),                       
                 Points = c(30, 20, 15, 35, 50),
                 Users = c("User1", "User2", "User3", "User4", "User5"))
 
# Create a Scatter Plot
ggplot(DF,aes(Year, Points, color = Users))+
  geom_point(size = 10)


Output:

Simple Scatter Plot with Legend

Similar Reads

Changing the order of Legend to Desired Order :

...

Reversing the Order of Legend

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) because we only want to change the order of legend. To copy DF to newDF, we simply assign DF to newDF....