Change Position of ggplot2 Legend in R (5 Examples)
In this post you’ll learn how to change the position of ggplot2 legends in the R programming language.
Preparing the Examples
data(iris) # Loading iris data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading iris data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
Example 1: Draw ggplot2 Legend at the Right Side of a Plot
my_plot <- ggplot(iris, aes(x = Sepal.Width, # ggplot2 legend right side y = Petal.Width, col = Species)) + geom_point() my_plot # Showing plot in RStudio |
my_plot <- ggplot(iris, aes(x = Sepal.Width, # ggplot2 legend right side y = Petal.Width, col = Species)) + geom_point() my_plot # Showing plot in RStudio
Example 2: Draw ggplot2 Legend at the Bottom of a Plot
my_plot + # ggplot2 legend below graph theme(legend.position = "bottom") |
my_plot + # ggplot2 legend below graph theme(legend.position = "bottom")
Example 3: Draw ggplot2 Legend at the Left Side of a Plot
my_plot + # ggplot2 legend left side theme(legend.position = "left") |
my_plot + # ggplot2 legend left side theme(legend.position = "left")
Example 4: Draw ggplot2 Legend at the Top of a Plot
my_plot + # ggplot2 legend above graph theme(legend.position = "top") |
my_plot + # ggplot2 legend above graph theme(legend.position = "top")
Example 5: Manually Set Position of ggplot2 Legend (Inside Plot)
my_plot + # ggplot2 legend within graph theme(legend.position = c(0.8, 0.5)) |
my_plot + # ggplot2 legend within graph theme(legend.position = c(0.8, 0.5))