How can I change the legend position in ggplot2?

The process of changing the legend position in ggplot2 involves altering the code or function used to create the graph. This can be achieved by specifying the desired position in the legend.position argument, which can be set to “top”, “bottom”, “left”, or “right”. Alternatively, the legend can be manually moved by adjusting the x and y coordinates using the legend.justification and legend.margin arguments. This allows for greater customization and control over the placement of the legend in the graph. Overall, changing the legend position in ggplot2 requires a basic understanding of the code and functions used to create the graph, and can be easily achieved with a few adjustments.

Change Legend Position in ggplot2 (With Examples)


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

x