請先確認 Excel 檔與 R 程式位於同一個資料夾,並依自己的檔名與欄位名稱調整語法。
01載入套件與資料
library(readxl)
library(dplyr)
library(janitor)
library(ggplot2)
data <- read_excel("demo_polisci_中文.xlsx")
02查看原始年齡分布
data |>
ggplot(aes(x = 年齡)) +
geom_histogram(
binwidth = 5,
boundary = 0,
fill = "#3976A8",
color = "white"
) +
labs(
title = "受訪者年齡分布",
x = "年齡",
y = "人數"
) +
theme_minimal(base_family = "Microsoft JhengHei")
03依指定切點建立年齡組
data <- data |>
mutate(
年齡組 = cut(
年齡,
breaks = c(18, 30, 40, 50, 60, Inf),
labels = c(
"18–29歲",
"30–39歲",
"40–49歲",
"50–59歲",
"60歲以上"
),
right = FALSE,
include.lowest = TRUE,
ordered_result = TRUE
)
)
04製作年齡組次數分配表
tab_age_group <- data |>
tabyl(年齡組) |>
adorn_totals("row") |>
adorn_pct_formatting(digits = 1)
tab_age_group
05繪製年齡組長條圖
age_plot <- data |>
filter(!is.na(年齡組)) |>
ggplot(aes(x = 年齡組)) +
geom_bar(
fill = "#3976A8",
color = "white"
) +
labs(
title = "受訪者年齡分布",
x = "年齡組",
y = "人數"
) +
theme_minimal(base_family = "Microsoft JhengHei")
age_plot
選用快速建立每 10 歲一組
data <- data |>
mutate(
年齡組 = cut(
年齡,
breaks = c(seq(0, 100, by = 10), Inf),
labels = c(
paste0(
seq(0, 90, by = 10),
"–",
seq(9, 99, by = 10),
"歲"
),
"100歲以上"
),
right = FALSE,
include.lowest = TRUE,
ordered_result = TRUE
)
)
選用儲存圖檔
ggsave(
filename = "年齡組次數分配圖.png",
plot = age_plot,
width = 10,
height = 6,
dpi = 300,
bg = "white"
)