...

/

Customizing Legends and Margins with ggplot2

Customizing Legends and Margins with ggplot2

Learn how to customize plot legends and margins in ggplot2.

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.

Press + to interact
df <- gapminder %>%
filter(country %in% c("Germany", "Sweden","Italy"))
chart <- ggplot(df)+
geom_area(aes(x = year, y = gdpPercap, fill = country))+
theme_bw()+
scale_fill_manual(values = c("#1DD3B0","#5DA9E9","#03045E"))
chart
  • Lines 1–2: We create a new df data frame and store the filtered data of the gapminder dataset using the filter() function. The new df data frame will only include the rows where the country is Germany, Sweden, and Italy.
  • Line 3: We create a new object named chart and use the <- assignment operator for storing the graph in the chart object. We initialize a new ggplot object with the ggplot() function and pass the df data frame. Using the + operator, we add a layer to the ggplot object.
  • Line 4: We use the geom_area() function to create an area chart where we use the aes() function for mapping the year variable to the x-axis and gdpPercap variable to the y-axis. We also group the data by the country variable using the color argument.
  • Line 5: We use the theme_bw() function for changing the default gray theme to a black and white theme.
  • Line 6: We use the scale_color_manual() function to specify different colors for the area chart.

The chart above shows that the default ...

Access this course and 1400+ top-rated courses and projects.