0
votes

I'm graphing a line plot in ggplot of numbers of migrants to a city over x years, based on country of origin. Each country is graphed as its own line, plotted on a graph against other countries, over a period of five years.

I want to order the legend by country from largest to smallest total sum of migrants over the x years, regardless of the total number of countries, instead of alphabetically as it is now.

I've tried using forcats commands such as fct_relevel, but haven't been able to find anything other than doing it manually, which can be time consuming for multiple graphs.

My data frame has variables year, country, and number_migrants, and each observation is a year-country pair.

library(tidyverse)
g <- ggplot(migrants, aes(x=year, y=number_migrants, col=country)) + 
geom_line() 

Current example: enter image description here

1

1 Answers

2
votes

You need fct_reorder

library(dplyr)
library(forcats)
migrants %>%
  mutate(
    country = fct_reorder(country, number_migrants, .desc = TRUE)
  ) %>%
  ggplot(migrants, aes(x=year, y=number_migrants, col=country)) + 
  geom_line()