ggguides provides position helpers that handle legend placement
without requiring knowledge of ggplot2’s theme system. Each function
sets the appropriate combination of legend.position,
legend.justification, and legend.box.just to
achieve proper alignment.
p <- ggplot(mtcars, aes(mpg, wt, color = factor(cyl))) +
geom_point(size = 3) +
labs(color = "Cylinders")
p + legend_left() + ggtitle("Left")
p + legend_right() + ggtitle("Right")When placing legends at the top or bottom, the legend is automatically oriented horizontally:
Use the align_to parameter to control how the legend
aligns with the plot. The difference is most visible when there’s a
y-axis label:
p_labeled <- p + labs(title = "Fuel Economy", y = "Weight (1000 lbs)")
# Default: align to panel (legend aligns with the plot area)
p_labeled + legend_top() + ggtitle("Panel alignment (default)")
# Align to full plot (legend spans title/axis labels too)
p_labeled + legend_top(align_to = "plot") + ggtitle("Plot alignment")legend_inside() places the legend within the plot panel.
You can use either coordinate values or named shortcuts.
Available shortcuts: "topright", "topleft",
"bottomright", "bottomleft",
"center"
p + legend_inside(position = "topright") + ggtitle("Top right")
p + legend_inside(position = "bottomleft") + ggtitle("Bottom left")For precise control, specify x/y coordinates (0-1 scale) and justification:
Control legend entry direction independently of position:
| Function | Position | Auto-Direction |
|---|---|---|
legend_left() |
Left of panel | Vertical |
legend_right() |
Right of panel | Vertical |
legend_top() |
Above panel | Horizontal |
legend_bottom() |
Below panel | Horizontal |
legend_inside() |
Inside panel | Unchanged |
legend_none() |
Hidden | N/A |
Learn more: