R语言UsingR包npdb数据集金额统计与图表实现问题咨询
前置操作
先加载所需依赖和数据集,所有后续代码均基于此环境运行:
# 加载数据集包 library(UsingR) data(npdb) # 如使用tidyverse语法/ggplot2可视化,需提前加载对应包 library(dplyr) library(ggplot2)
1. 计算每个ear对应总金额并生成饼图
先按ear分组求和得到总金额,再传入绘图函数即可:
# 按ear分组计算总金额 ear_amount_sum <- aggregate(amount ~ ear, npdb, sum) # 基础R绘图版饼图 pie(ear_amount_sum$amount, labels = ear_amount_sum$ear, main = "各ear总金额占比") # ggplot2美化版饼图 ggplot(ear_amount_sum, aes(x = "", y = amount, fill = as.factor(ear))) + geom_col(color = "white") + coord_polar(theta = "y") + labs(title = "各ear总金额占比", fill = "ear") + theme_void()
2. 提取每个州最高金额对应的记录及ID
按州分组后取金额最高的行即可,可自行调整参数控制是否保留并列最高的记录:
state_top_records <- npdb %>% group_by(state) %>% # with_ties设为TRUE可保留同一州多个相同最高金额的记录,设为FALSE仅取第一条 slice_max(amount, n = 1, with_ties = FALSE) %>% select(state, ID, amount) # 输出所有州的结果 print(state_top_records, n = Inf)
3. 绘制金额数据的直方图
直接传入金额列绘图即可,由于金额数据普遍右偏,可选择对数转换后绘制以获得更清晰的分布特征:
# 基础R绘图版原始金额直方图 hist(npdb$amount, breaks = 30, col = "lightblue", main = "金额分布直方图", xlab = "金额") # 基础R绘图版对数转换后金额直方图 hist(log(npdb$amount), breaks = 30, col = "lightgreen", main = "对数转换后金额分布直方图", xlab = "log(金额)") # ggplot2版原始金额直方图 ggplot(npdb, aes(x = amount)) + geom_histogram(bins = 30, fill = "lightblue", color = "black") + labs(title = "金额分布直方图", x = "金额", y = "频数") + theme_minimal() # ggplot2版对数转换后金额直方图 ggplot(npdb, aes(x = log(amount))) + geom_histogram(bins = 30, fill = "lightgreen", color = "black") + labs(title = "对数转换后金额分布直方图", x = "log(金额)", y = "频数") + theme_minimal()
内容的提问来源于stack exchange,提问作者MiRAY
相关产品推荐
相关产品推荐

