Reordering elements in the plot
As shown in the video, use mutate() and fct_reorder() to change the factor level ordering of a variable.
This exercise is part of the course
Communicating with Data in the Tidyverse
Exercise instructions
- Use
fct_reorder()in theforcatspackage to reorder thecountryfactor variable by weekly working hours in the year 2006.- To do that, specify the correct summary function as the third argument of
fct_reorder. It should arrange thecountryfactor levels by the last element in theworking_hoursvariable.
- To do that, specify the correct summary function as the third argument of
- In order to do the above, you first need to
arrange()the data set byyear– so 1996 is always first in each country group and 2006 is always last.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(forcats)
# Reorder country factor levels
ilo_data <- ilo_data %>%
# Arrange data frame
arrange(___) %>%
# Reorder countries by working hours in 2006
mutate(country = fct_reorder(___,
___,
___))
# Plot again
ggplot(ilo_data) +
geom_path(aes(x = working_hours, y = country),
arrow = arrow(length = unit(1.5, "mm"), type = "closed")) +
geom_text(
aes(x = working_hours,
y = country,
label = round(working_hours, 1))
)