A number of settings that affect the overall display of the legends are controlled through the theme system. You’ll learn more about that in Section 17.2, but for now, all you need to know is that you modify theme settings with the
The position and justification of legends are controlled by the theme setting
legend.position, which takes values “right”, “left”, “top”, “bottom”, or “none” (no legend).
ggplot(toy, aes(up, up)) + base <- geom_point(aes(colour = txt), size = 3) + xlab(NULL) + ylab(NULL) + theme(legend.position = "left") base + theme(legend.position = "right") # the default base + theme(legend.position = "bottom") base + theme(legend.position = "none")base
Switching between left/right and top/bottom modifies how the keys in each legend are laid out (horizontal or vertically), and how multiple legends are stacked (horizontal or vertically). If needed, you can adjust those options independently:
legend.direction: layout of items in legends (“horizontal” or “vertical”).
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”).
Alternatively, if there’s a lot of blank space in your plot you might want to place the legend inside the plot. You can do this by setting
legend.position to a numeric vector of length two. The numbers represent a relative location in the panel area:
c(0, 1) is the top-left corner and
c(1, 0) is the bottom-right corner. You control which corner of the legend the
legend.position refers to with
legend.justification, which is specified in a similar way. Unfortunately positioning the legend exactly where you want it requires a lot of trial and error.
ggplot(toy, aes(up, up)) + base <- geom_point(aes(colour = txt), size = 3) + theme(legend.position = c(0, 1), legend.justification = c(0, 1)) base + theme(legend.position = c(0.5, 0.5), legend.justification = c(0.5, 0.5)) base + theme(legend.position = c(1, 0), legend.justification = c(1, 0))base
There’s also a margin around the legends, which you can suppress with
legend.margin = unit(0, "mm").