在R中使用ggplot创建等频率(等Bin数)直方图的方法
用ggplot绘制等频率直方图的实现方法
一、整合classInt生成的区间到ggplot
如果你已经通过classInt包生成了等频率区间,只需提取区间断点,就能直接对接ggplot的绘图逻辑,有两种常用方式:
方法1:直接传入断点到geom_histogram
library(classInt) library(ggplot2) # 生成10个等频率区间 int <- classIntervals(dataset$Depth, n = 10, style = "quantile") breaks <- int$brks # 绘制直方图 ggplot(dataset, aes(x = Depth)) + geom_histogram(breaks = breaks, fill = "steelblue", color = "white") + labs(title = "等频率直方图", x = "Depth", y = "频数")
方法2:先分组再用geom_bar绘制
如果需要更清晰地展示每个区间的频数,可以先把Depth按区间分组,再用柱状图呈现:
# 给数据集添加分组列,include.lowest确保最小值被包含在第一组 dataset$depth_group <- cut(dataset$Depth, breaks = breaks, include.lowest = TRUE) ggplot(dataset, aes(x = depth_group)) + geom_bar(fill = "steelblue", color = "white") + labs(title = "等频率直方图(按区间分组)", x = "Depth区间", y = "频数") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转x轴标签避免重叠
二、无需classInt的替代方法
方法1:用dplyr的ntile快速分组
ntile函数可以直接把数据分成指定数量的等频率组,适合快速绘图:
library(dplyr) library(ggplot2) dataset %>% mutate(depth_group = ntile(Depth, n = 10)) %>% # 分成10个等频率组 count(depth_group) %>% ggplot(aes(x = factor(depth_group), y = n)) + geom_col(fill = "coral", color = "white") + labs(title = "等频率直方图(ntile分组)", x = "组编号", y = "频数")
方法2:直接用quantile生成断点
如果需要显示具体的区间范围,直接用quantile生成分位数断点,再结合cut分组:
# 生成0到100%的分位数断点(10组对应11个断点) breaks_quantile <- quantile(dataset$Depth, probs = seq(0, 1, 0.1), na.rm = TRUE) dataset %>% mutate(depth_group = cut(Depth, breaks = breaks_quantile, include.lowest = TRUE)) %>% count(depth_group) %>% ggplot(aes(x = depth_group, y = n)) + geom_col(fill = "coral", color = "white") + labs(title = "等频率直方图(quantile断点)", x = "Depth区间", y = "频数") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
内容的提问来源于stack exchange,提问作者Elle
相关产品推荐
相关产品推荐

