如何使用Ggplot2绘制不等分箱宽无间隔的频率密度直方图
ggplot实现不等宽无空隙频率密度直方图
实现思路
你已经有汇总好的分箱区间和对应频率密度,不需要调用ggplot的内置分箱统计逻辑,直接使用geom_col指定对应柱子宽度即可实现需求。
完整代码
# 加载依赖包 library(ggplot2) # 构造分箱数据集 bin_data <- data.frame( bin_left = c(0, 5, 15, 20, 30), bin_right = c(5, 15, 20, 30, 40), freq_density = c(0.2, 0.1, 1.2, 0.4, 0.4) ) # 计算分箱宽度和X轴显示标签 bin_data$bin_width <- bin_data$bin_right - bin_data$bin_left bin_data$x_label <- paste0(bin_data$bin_left, "≤x<", bin_data$bin_right) # 绘图 ggplot(bin_data, aes(x = (bin_left + bin_right)/2, y = freq_density)) + geom_col( width = bin_data$bin_width, fill = "#5698c3", color = "black" # 加黑色边框更清晰区分分箱 ) + scale_x_continuous( breaks = (bin_data$bin_left + bin_data$bin_right)/2, labels = bin_data$x_label, name = "数值区间" ) + ylab("频率密度") + theme_bw()
效果说明
- 柱子宽度与分箱宽度完全匹配,分箱之间无空隙
- X轴直接展示要求的区间标签,符合阅读习惯
- Y轴高度与给定的频率密度值完全对应
内容的提问来源于stack exchange,提问作者Stata_user
相关产品推荐
相关产品推荐

