You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于员工数加权,用ggplot绘制薪资分布直方图

按员工数加权的薪资直方图绘制方案

我要展示某一职业的薪资分布,用的是BLS按县统计的数据。现在用ggplot画直方图的代码里,y轴统计的是县的数量,这导致只有10名员工、平均薪资5万的县,和有100名员工、平均薪资8万的县权重完全一样。我知道可以把每行数据按员工数展开,但想找更高效的方法。试过去设置y=avg_employees,但geom_histogram不允许同时用x和y参数。

现有绘图代码

ggplot(Construction[which(Construction$avg_annual_pay>0),], aes(x=avg_annual_pay)) + 
  geom_histogram(binwidth = 5000, colour="black", fill="white") + 
  scale_x_continuous(labels = label_comma())

数据示例

countyavg # employeesavg annual pay
13447000
290088000
38540000

数据获取补充代码

qcewGetIndustryData <- function (year, qtr, industry) {
  url <- "http://data.bls.gov/cew/data/api/YEAR/QTR/industry/INDUSTRY.csv"
  url <- sub("YEAR", year, url, ignore.case=FALSE)
  url <- sub("QTR", tolower(qtr), url, ignore.case=FALSE)
  url <- sub("INDUSTRY", industry, url, ignore.case=FALSE)
  read.csv(url, header = TRUE, sep = ",", quote="\"", dec=".", na.strings=" ", skip=0)
}

Construction <- qcewGetIndustryData("2015", "a", "1012")

数据预览

> head(Construction[,1:5])
  area_fips own_code industry_code agglvl_code size_code
1     01000        3          1012          53         0
2     01000        5          1012          53         0
3     01001        5          1012          73         0
4     01003        5          1012          73         0
5     01005        5          1012          73         0
6     01007        5          1012          73         0

解决方案

不用展开数据,直接在aes里添加weight参数,用员工数作为权重即可:

ggplot(Construction[which(Construction$avg_annual_pay>0),], 
       aes(x=avg_annual_pay, weight = avg_employees)) + 
  geom_histogram(binwidth = 5000, colour="black", fill="white") + 
  scale_x_continuous(labels = label_comma()) +
  labs(y = "员工总数") # 修改y轴标签,明确统计的是员工数量而非县数

原理说明

  • weight参数会让直方图在计算每个薪资区间的计数时,将每个县的基础计数(1)乘以对应的员工数,这样员工多的县会在直方图中占据更高的权重,反映真实的员工薪资分布,而非单纯的县域分布。
  • 这种方法无需复制数据行,内存占用更低,处理大规模数据时效率更高。

内容的提问来源于stack exchange,提问作者creetz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:41:06