ggplot2 will automatically build a legend
on your chart as soon as a shape feature is mapped to a variable in
aes() part of the
ggplot() call. So if you
legend will be available.
Here is an example based on the
mtcars dataset. This
post is gonna show how to use the
theme() function to
apply all type of customization on this default legend.
Note : this post is strongly inspired by the doc you get
??ggplot2::theme, give it a go!
labs() function allows to change the legend titles.
You can specify one title per section of the legend, i.e. per
aesthetics in use in the chart.
It is possible to remove a specific part or the whole legend thanks to
theme() and the
guides() function. See
You can place the legend literally anywhere.
To put it around the chart, use the
left. To put it inside the plot area, specify a vector
of length 2, both values going between 0 and 1 and giving the x and y
Note: the command
legend.justification sets the corner that
the position refers to.
Here are 4 examples showing how to customize the legend main features:
legend.box.: it is a rectangle that frames the legend. Give features with
legend.key: the key is the part showing the symbols. Note that symbols will automatically be the ones used on the chart
legend.text: here you can control the color, the size of the right part of the legend