This page aims to provide useful R code to custom the legend of your ggplot2 plots. More generally, the R graph gallery proposes 3 pages dedicated to the layout customisation: one concerning axis, one concerning background, and this one concerning legends.

Here we want to modify non-data components, and it is often done through the theme() command. This page is strongly inspired from the help page of ggplot2 (?theme). Also, do not hesitate to visit the very strong ggplot2 documentation for more information.

We start with this really basic plot relying on the mtcars dataset with a default legend:






Now we can change the title of the legend using labs():




You can easily remove one legend but not the other with guides():

To remove the legend use legend.position=”none” in theme().  To change its position but outside the plot use top, left, right or bottom. Or place inside the plot using relative coordinates between 0 and 1. The command legend.justification sets the corner that the position refers to.

Once your legend is at the right position, you can customize its appearance.

Not what you are looking for ? Make a new search !


Leave a Reply

Notify of