自訂 ggplot2 的誤差範圍圖
你應該已經在前一題的圖表裡發現一些問題。由於各郡沒有排序,讀者很難看出資料中的規律。特別是,當點依序排列時,誤差範圍圖會更有效果,因為排序能讓讀者理解各估計值相對於其他估計的不確定性。此外,圖表缺乏格式化,會讓讀者難以理解圖表的內容。在這個練習中,你會整理 ggplot2 的程式碼,繪製一張更具視覺吸引力的誤差範圍圖。
本練習屬於課程
在 R 中分析美國人口普查資料
練習說明
- 使用 tidyverse 的
str_replace()函式,從郡名中移除" County, Maine"。 - 在圖中依家庭收入中位數由高到低重新排序各郡。
- 使用
subtitle將副標題設為「Counties in Maine」,為這些資料點補充共通資訊。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Remove unnecessary content from the county's name
maine_inc2 <- maine_inc %>%
mutate(NAME = ___(NAME, " County, Maine", ""))
# Build a margin of error plot incorporating your modifications
ggplot(maine_inc2, aes(x = estimate, y = ___(NAME, estimate))) +
geom_errorbarh(aes(xmin = ___ - moe, xmax = estimate + ___)) +
geom_point(size = 3, color = "darkgreen") +
theme_grey(base_size = 14) +
labs(title = "Median household income",
___ = "Counties in Maine",
x = "ACS estimate (bars represent margins of error)",
y = "") +
scale_x_continuous(labels = scales::dollar)