• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Data Viz with Python and R

Learn to Make Plots in Python and R

  • Home
  • Python Viz
  • Seaborn
  • Altair
  • R Viz
  • ggplot2
  • About
    • Privacy Policy
  • Show Search
Hide Search

How to make legend order match with plot

datavizpyr · September 15, 2023 ·

In this post we will learn how to make a line plot such that data on the plot matches with the legend order. We will use forcats package’s fct_reorder2() function.

Let us load the packages needed.

library(tidyverse)
library(gapminder)
theme_set(theme_bw(16))

We will use gapminder data set to make a line plot.

gapminder %>% head()

# A tibble: 6 × 6
  country     continent  year lifeExp      pop gdpPercap
  <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
1 Afghanistan Asia       1952    28.8  8425333      779.
2 Afghanistan Asia       1957    30.3  9240934      821.
3 Afghanistan Asia       1962    32.0 10267083      853.
4 Afghanistan Asia       1967    34.0 11537966      836.
5 Afghanistan Asia       1972    36.1 13079460      740.
6 Afghanistan Asia       1977    38.4 14880372      786.

First let us compute average life expectancy per year and continent.

df <- gapminder %>% 
  group_by(continent,year) %>%
  summarize(mean_life = mean(lifeExp))
df

# A tibble: 60 × 3
# Groups:   continent [5]
   continent  year mean_life
   <fct>     <int>     <dbl>
 1 Africa     1952      39.1
 2 Africa     1957      41.3
 3 Africa     1962      43.3
 4 Africa     1967      45.3
 5 Africa     1972      47.5
 6 Africa     1977      49.6
 7 Africa     1982      51.6
 8 Africa     1987      53.3
 9 Africa     1992      53.6
10 Africa     1997      53.6
# ℹ 50 more rows

We will use the summarized gapminder data to make a lineplot between year and average life expectancy for each continent. We have made line plot with points for each continent using ggplot2. We have also colored the plot by continent variable and that creates legend for the plot.

df %>%
  ggplot(aes(year, mean_life, 
             color=continent))+
  geom_point()+
  geom_line()
ggsave("how_to_make_legend_order_match_with_plot_data_order.png")

Note that the default legend order does not match with the order of lines in the line plot.

How to make legend order match with plot data order in R
How to make legend order match with plot data order in R

Matching legend order with plot order with fct_reorder2()

To make the legend order match with the plot line order, we use fct_reorder2() function that takes three argument as input. The first argument is the variable we want to order and remaining two variables are the two main variables in the plot.

df %>% 
  ggplot(aes(year, mean_life, color=fct_reorder2(continent,year, mean_life)))+
  geom_point()+
  geom_line()
ggsave("make_legend_order_match_plot_data_order_with_fct_reorder2.png")

Reordering legend order with fct_reorder2()
Reordering legend order with fct_reorder2()

We have successfully reordered the legends, but we need to fix the legend title. We can change the legend title with labs(color=”continent”).

df %>% 
  ggplot(aes(year, mean_life, 
             color = fct_reorder2(continent, year, mean_life)))+
  geom_point()+
  geom_line()+
  labs(color="continent")
ggsave("make_legend_order_match_with_plot_data_order_with_fct_reorder2.png")
Match legend order with plot data order with fct_reorder2
Match legend order with plot data order with fct_reorder2

Related posts:

Customizing Mean mark to boxplot with ggplot2How To Show Mean Value in Boxplots with ggplot2? Scatterplot with marginal multi-histogram with ggExtraHow To Make Scatterplot with Marginal Histograms in R? Default ThumbnailHow to Move Facet strip label to the bottom Default ThumbnailHow to change axis tick label size in ggplot2

Filed Under: ggplot2, R Tagged With: forcats fct_reorder2(), make legend order match plot

Primary Sidebar

Tags

Altair barplot Boxplot boxplot python boxplot with jiitered text labels Bubble Plot Color Palette Countplot Density Plot Facet Plot gganimate ggplot2 ggplot2 Boxplot ggplot2 error ggplot boxplot ggridges ggtext element_markdown() Grouped Barplot R heatmap heatmaps Histogram Histograms Horizontal boxplot Python lollipop plot Maps Matplotlib Pandas patchwork pheatmap Pyhon Python R RColorBrewer reorder boxplot ggplot Ridgeline plot Scatter Plot Scatter Plot Altair Seaborn Seaborn Boxplot Stock Price Over Time Stripplot UpSetR Violinplot Violin Plot World Map ggplot2

Buy Me a Coffee

Copyright © 2025 · Daily Dish Pro on Genesis Framework · WordPress · Log in

Go to mobile version