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

r graph figure 1 change position ggplot2 legend

Example 2: Draw ggplot2 Legend at the Bottom of a Plot

my_plot +                                       # ggplot2 legend below graph
  theme(legend.position = "bottom")

r graph figure 2 change position ggplot2 legend

Example 3: Draw ggplot2 Legend at the Left Side of a Plot

my_plot +                                       # ggplot2 legend left side
  theme(legend.position = "left")

r graph figure 3 change position ggplot2 legend

Example 4: Draw ggplot2 Legend at the Top of a Plot

my_plot +                                       # ggplot2 legend above graph
  theme(legend.position = "top")

r graph figure 4 change position ggplot2 legend

Example 5: Manually Set Position of ggplot2 Legend (Inside Plot)

my_plot +                                       # ggplot2 legend within graph
  theme(legend.position = c(0.8, 0.5))

r graph figure 5 change position ggplot2 legend

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top