重新排序圖中的元素
如同影片所示,使用 mutate() 和 fct_reorder() 來改變某個變數的因子層級順序。
本練習屬於課程
在 Tidyverse 中以資料溝通
練習說明
- 使用
forcats套件中的fct_reorder(),依 2006 年的每週工時來重新排序因子變數country。- 為此,請在
fct_reorder的第三個引數指定正確的摘要函式。它應該以working_hours變數中的「最後」一個元素來決定country因子層級的排序。
- 為此,請在
- 為了做到上述步驟,你需要先用
arrange()依year對資料集排序——讓 1996 年在各國群組中一律排在最前,而 2006 年一律排在最後。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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))
)