如何用ggplot2基于预计算计数绘制可调整分箱的直方图?
用ggplot2基于预计算计数数据绘制可自定义分箱的直方图
我已经有按数值预计算好的计数数据,想用ggplot2绘制直方图。目前用geom_col生成的柱状图不符合需求,希望能像geom_histogram的bins参数那样调整分箱方式。
原始数据与初始代码
library(ggplot2) library(dplyr) # 定义数据框 df <- data.frame( value = c(10,11,12,13,14,15,16,17,18, 19,2,20,21,22,23,24,25,26,27,28), num_customers = c(208,179,232,335,263,277,32898, 325,332,461,3441,415,19584,392,521,513,674,24114, 807,692) ) # 查看数据框 df #> value num_customers #> 1 10 208 #> 2 11 179 #> 3 12 232 #> 4 13 335 #> 5 14 263 #> 6 15 277 #> 7 16 32898 #> 8 17 325 #> 9 18 332 #> 10 19 461 #> 11 2 3441 #> 12 20 415 #> 13 21 19584 #> 14 22 392 #> 15 23 521 #> 16 24 513 #> 17 25 674 #> 18 26 24114 #> 19 27 807 #> 20 28 692 # 绘制的不理想柱状图 df %>% ggplot( aes( x = value, y = num_customers ) ) + geom_col()

解决方案:先分箱再绘图
要实现类似geom_histogram的分箱效果,核心是先对value进行分箱,再按分箱组汇总客户数,最后绘图。
方法1:提前用cut()分箱并汇总
手动指定分箱数量或区间,先处理数据再绘图:
# 设置5个分箱,include.lowest确保最小值被包含在第一个区间 df_binned <- df %>% mutate(value_bin = cut(value, bins = 5, include.lowest = TRUE)) %>% group_by(value_bin) %>% summarise(total_customers = sum(num_customers)) # 绘制分箱后的柱状图 ggplot(df_binned, aes(x = value_bin, y = total_customers)) + geom_col(fill = "#2E8B57", color = "black") + labs(x = "Value 分箱", y = "总客户数", title = "按自定义分箱统计的客户数") + theme_minimal()
如果需要更精准的分箱控制,直接指定区间即可,比如:
# 手动指定分箱区间 df_binned_custom <- df %>% mutate(value_bin = cut(value, breaks = c(0,5,10,15,20,25,30), include.lowest = TRUE)) %>% group_by(value_bin) %>% summarise(total_customers = sum(num_customers))
方法2:用stat_summary_bin直接在绘图时分箱
无需提前处理数据,用ggplot内置的统计函数完成分箱和汇总:
ggplot(df, aes(x = value, y = num_customers)) + stat_summary_bin(fun = sum, geom = "col", bins = 5, fill = "#4682B4", color = "black") + labs(x = "Value 分箱", y = "总客户数", title = "用stat_summary_bin分箱的直方图") + theme_minimal()
这里fun = sum表示对每个分箱内的num_customers求和,geom = "col"指定用柱状图展示结果。
内容的提问来源于stack exchange,提问作者joshbrows
相关产品推荐
相关产品推荐

