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