11.1 C
London
Sunday, July 7, 2024
HomeTidyverse in Rggplot2 in RHow to Change Legend Position in ggplot2 (With Examples)

How to Change Legend Position in ggplot2 (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to specify the position of a ggplot2 legend:

theme(legend.position = "right")

The following examples show how to use this syntax in practice with the built-in iris dataset in R.

Example: Place Legend On Outside of Plot

You can directly tell ggplot2 to place the legend on the “top”, “right”, “bottom” or “left” side of the plot.

For example, here’s how to place the legend on the top of the plot:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
       geom_point() +
       theme(legend.position = "top")

Example of ggplot2 title on top of plot

And here’s how to place the legend on the bottom of the plot:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
       geom_point() +
       theme(legend.position = "bottom")

Example of title on bottom of ggplot2

Example: Place Legend On Inside of Plot

You can also specify the exact (x, y) coordinates to place the legend on the inside of the plot.

For example, here’s how to place the legend inside the top right corner:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
       geom_point() +
       theme(legend.position = c(.9, .9))

And here’s how to place the legend inside the bottom right corner:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
       geom_point() +
       theme(legend.position = c(.9, .1))

Example: Remove Legend Completely

You can also remove the legend from a plot in ggplot2 entirely by specifying legend.position=”none” as follows:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
       geom_point() +
       theme(legend.position = "none")

Additional Resources

How to Change Legend Size in ggplot2
How to Change the Legend Title in ggplot2
A Complete Guide to the Best ggplot2 Themes

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories