R语言如何绘制各property_area贷款获批率聚合百分比条形图
R语言绘制不同区域贷款获批百分比条形图的最简实现
你之前用ggplot没成功大概率是直接用了原始数据集的计数逻辑,没有提前计算获批比例,下面是两种可直接运行的实现方案:
前置依赖
需要先安装加载ggplot2(或完整的tidyverse套件),未安装的话先运行:install.packages("ggplot2")
方案1:先统计比例再绘图(逻辑清晰,不易出错)
# 加载包 library(ggplot2) library(dplyr) # 构造示例数据集 df <- data.frame( loan_status = c('Y','N','Y','N','Y','N'), property_area = c('Semiurban', 'Urban', 'Rural', 'Semiurban', 'Urban', 'Rural') ) # 按区域统计获批百分比 plot_df <- df %>% group_by(property_area) %>% summarise(approve_pct = mean(loan_status == 'Y') * 100) # 绘制条形图 ggplot(plot_df, aes(x = property_area, y = approve_pct)) + geom_col(fill = "#2c7fb8") + labs(x = "房产区域", y = "贷款获批百分比(%)", title = "不同区域贷款获批情况") + theme_bw()
方案2:无需提前汇总数据,直接调用ggplot内置统计能力
library(ggplot2) # 构造示例数据集 df <- data.frame( loan_status = c('Y','N','Y','N','Y','N'), property_area = c('Semiurban', 'Urban', 'Rural', 'Semiurban', 'Urban', 'Rural') ) # 一步绘图 ggplot(df, aes(x = property_area, y = as.numeric(loan_status == 'Y') * 100)) + geom_bar(stat = "summary", fun = "mean", fill = "#2c7fb8") + labs(x = "房产区域", y = "贷款获批百分比(%)", title = "不同区域贷款获批情况") + theme_bw()
两种方案输出结果完全一致,你可以根据自己的需求调整颜色、主题、标签等样式参数。
内容的提问来源于stack exchange,提问作者Ricardo Vilaça
相关产品推荐
相关产品推荐

