Legends in ggplot2

In ggplot2, the legend is an essential aspect of a graph as it helps to identify the different elements of the plot. Legends get automatically generated when we map variables to different attributes. We can customize the legends using the theme() function. By default, the legend is displayed on the right side of the plot, but it can be customized to be placed in different positions or to have a specific appearance.

Let’s first create an area chart using the gapminder dataset from the gapminder package. We’ll then customize the legends and margins on our graph.

Get hands-on with 1200+ tech skills courses.