[R] How to Position the Legend Inside a Plot in ggplot2

Wait 5 sec.

[This article was first published on R on Zhenguo Zhang's Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.Zhenguo Zhang’s Blog https://fortune9.netlify.app/2026/05/30/r-position-legend-inside-plot/ –By default, ggplot2 places the legend outside the plot area (usually on the right). However, sometimes you may want to move the legend inside the plot to save space or improve the layout. This post explores how to achieve this using theme() parameters.Example 1: Basic Usage of legend.positionThe simplest way to move a legend inside the plot is by providing a numeric vector of length two to the legend.position argument in theme(). These coordinates represent the relative position within the plot panel, ranging from 0 to 1. Check thesection on “Key Positioning Controls” at the end for a detailed explanation of the coordinate system.library(ggplot2)ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) + geom_point(size = 3) + theme_bw() + theme(legend.position = c(0.8, 0.8))Example 2: Fine-Tuning with Justification and BackgroundWhen you place a legend inside, you often need to adjust which part of the legend box aligns with your coordinates and handle the background if it obscures data.legend.justification: Controls the anchor point of the legend box. For example, c("right", "top") means the top-right corner of the legend box will be placed at the specified coordinates.legend.background: Use element_blank() to make the background transparent.ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) + geom_point(size = 3) + theme_bw() + theme( legend.position = c(1, 1), legend.justification = c("right", "top"), legend.background = element_blank() )Example 3: Positioning in Faceted PlotsMoving the legend inside a faceted plot works similarly: the whole figure is considered asone plot for the coordinate system. You can use the coordinates to place it within one of the empty spaces or over a specific panel.In the following example, the legend is placed in the bottom center of the plot, and a background is added to improve readability:ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) + geom_point(size = 3) + facet_wrap(~am) + theme_bw() + theme( legend.position = c(0.5, 0.2), legend.background = element_rect(fill = "white", color = "grey80") )Example 4: The “Empty Space” Trick for Faceted PlotsIf you have a panel which doesn’t have any data, and then it is the perfect spot toplace legend. To show this, the facet variable carb has only 3 values, and wewill make a 2×2 facet grid. We will also remove the background and border of the legend.The following example shows this:# Use 3 categories to leave the 4th spot in a 2x2 grid emptymtcars_subset