從 Histogram 到 KDE
在這些練習中,我們會查看資料中一個子集:針對 "Heavy Duty Truck" 開出的告發單。我們可能是一位懂資料的卡車司機,想知道在路上最危險的時段是什麼時候。請注意,這裡的樣本量只有 32 個觀測值。
下方是用 ggplot 繪製預設 histogram 的程式碼。不意外地,效果並不好。資料量不足以填滿 30 個 bins,讓圖很難閱讀,也難以掌握資料。請將幾何圖層改為使用 geom_density() 的 KDE。最後,為了讓視覺化更透明,替圖表加上一個副標題,說明你在 KDE 中使用的分箱寬度。
本練習屬於課程
R 視覺化最佳實務
練習說明
- 將 histogram 幾何改為密度圖(
geom_density())。 - 將預設的寬度調整為
1.5單位。 - 在圖上加入
subtitle"Gaussian kernel SD = 1.5",告訴讀者你的核心「binwidth」。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# filter data to just heavy duty trucks
truck_speeding <- md_speeding %>%
filter(vehicle_type == "Heavy Duty Truck")
ggplot(truck_speeding, aes(x = hour_of_day)) +
# switch to density with bin width of 1.5, keep fill
geom_histogram(fill = 'steelblue') +
# add a subtitle stating binwidth
labs(title = 'Citations by hour')