The theme()
documentation page has several examples showing how to place legends in different spots:
Modify components of a theme — theme • ggplot2 (legend stuff starts about halfway through the examples)
The legend.position
keywords control where the legend appears outside the plot area. To put a legend inside the plot, you supply legend.position
as coordinates on a relative scale that runs from [0,0] in the lower left to [1,1] in the upper right. You'll usually want to use legend.justification
, too — this tells ggplot
which part of the legend box should align with the coordinates. By default it's the center point of the box, which is not ideal if you want the legend all the way to one side of the plot area.
library(tidyverse)
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(color = factor(cyl))) +
labs(
x = "Weight (1000 lbs)",
y = "Fuel economy (mpg)",
color = "Cylinders"
) + theme(
legend.position = c(0.95, 0.95),
legend.justification = c("right", "top")
)
Created on 2018-09-30 by the reprex package (v0.2.1)
All the theme
elements that modify legends begin with legend.
, so you can use autocomplete to explore them. Or you can read about them in the theme()
documentation. Here's the summary:
legend.background
background of legend (element_rect; inherits from rect)
legend.margin
the margin around each legend (margin)
legend.spacing
the spacing between legends (unit)
legend.spacing.x
the horizontal spacing between legends (unit); inherits from legend.spacing
legend.spacing.y
the horizontal spacing between legends (unit); inherits from legend.spacing
legend.key
background underneath legend keys (element_rect; inherits from rect)
legend.key.size
size of legend keys (unit)
legend.key.height
key background height (unit; inherits from legend.key.size)
legend.key.width
key background width (unit; inherits from legend.key.size)
legend.text
legend item labels (element_text; inherits from text)
legend.text.align
alignment of legend labels (number from 0 (left) to 1 (right))
legend.title
title of legend (element_text; inherits from title)
legend.title.align
alignment of legend title (number from 0 (left) to 1 (right))
legend.position
the position of legends ("none", "left", "right", "bottom", "top", or two-element numeric vector)
legend.direction
layout of items in legends ("horizontal" or "vertical")
legend.justification
anchor point for positioning legend inside plot ("center" or two-element numeric vector) or the justification according to the plot area when positioned outside the plot
legend.box
arrangement of multiple legends ("horizontal" or "vertical")
legend.box.just
justification of each legend within the overall bounding box, when there are multiple legends ("top", "bottom", "left", or "right")
legend.box.margin
margins around the full legend area, as specified using margin()
legend.box.background
background of legend area (element_rect; inherits from rect)
legend.box.spacing
The spacing between the plotting area and the legend box (unit)