開始使用免費開始

重新排序圖中的元素

如同影片所示,使用 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))
          )
編輯並執行程式碼