開始使用免費開始

盒狀圖與機率密度圖

汽車的油耗通常與引擎大小有關(可用汽缸數來衡量)。若要探索這兩個變數之間的關係,你可以只用長條圖,不過在這個練習中,你會試試兩種替代做法:盒狀圖與機率密度圖。

本練習屬於課程

R 的探索式資料分析

檢視課程

練習說明

快速查看 unique(cars$ncyl) 會發現 ncyl 的可能層級比你想的多。這裡請把重點放在最常見的幾個層級。

  • cars 篩選為僅包含 4、6、或 8 缸車款,並將結果存為 common_cyl%in% 運算子在這裡很實用。
  • ncyl 分開,建立並排的 city_mpg 盒狀圖。
  • ncyl 上色,建立重疊的 city_mpg 機率密度圖。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Filter cars with 4, 6, 8 cylinders
common_cyl <- filter(___, ___)

# Create box plots of city mpg by ncyl
ggplot(___, aes(x = as.factor(___), y = ___)) +
  geom_boxplot()

# Create overlaid density plots for same data
ggplot(common_cyl, aes(x = ___, fill = as.factor(___))) +
  geom_density(alpha = .3)
編輯並執行程式碼