df <- mpg %>%
mutate(class = fct_lump_n(class, 5)) %>%
count(class) %>%
arrange(desc(n)) %>%
mutate(pct = round(100 * n / sum(n), 0),
label = paste0(class, "\n", pct, "%"),
class = factor(class, levels = class) # 按频数降序设置因子顺序
)
colors <- colorRampPalette(c("lightblue", "blue", "darkblue"))(nrow(df))
# 绘制饼图(极坐标 + 降序排列)
ggplot(df, aes(x = "", y = n, fill = class)) +
geom_bar(stat = "identity", width = 1) +
scale_fill_manual(values = colors) +
coord_polar(theta = "y", direction = -1) + # 逆时针方向排列
geom_text(aes(label = label),
col = "white",
position = position_stack(vjust = 0.5), size = 5) +
theme_void() +
theme(legend.position = "none")