基于校园纸板回收调研数据绘制箱线图的问题求助
问题排查:校园纸板回收数据箱线图绘制异常及NA值问题
问题背景
30人参与的校园纸板回收调研,数据范围为0至1000克以上,尝试按邮政编码plz分组统计各城镇数据并绘制箱线图时,出现两个问题:
- 聚合后的数据集
d.Daten_Agg存在大量NA值 - ggplot绘图报错
执行代码
d.Daten_Agg <- aggregate(list(kk_agg = d.Daten$k_kehrricht), list(plz = d.Daten$plz), function(x) round(sd(x, na.rm = TRUE), 1)) d.Daten_Agg ggplot(d.Daten_Agg, aes(y=d.Daten_Agg)) + stat_boxplot(geom="errorbar", width=0.5)+ geom_boxplot(fill="darkorchid3", outlier.color="darkorchid3", outlier.size=3, outlier.shape=8, width = 1) + ylab("Karton Kehrricht [kg]")+ theme(plot.title = element_text(hjust = 0.5, margin = margin(t = 10), size = 12, vjust=2, face = "bold")) + xlab("alle Daten")+ scale_x_discrete()
报错信息
第一次绘图报错
Don't know how to automatically pick scale for object of type <data.frame>. Defaulting to continuous. Error in `stat_boxplot()`: ! Problem while computing aesthetics. ℹ Error occurred in the 1st layer. Caused by error in `check_aesthetics()`: ! Aesthetics must be either length 1 or the same as the data (21) ✖ Fix the following mappings: `y` Run `rlang::last_trace()` to see where the error occurred.
修改y轴映射后报错
Error in ggplot(kk_agg, aes(y = kk_agg)) : object 'kk_agg' not found
问题分析与解决方案
1. 大量NA值的原因
你用aggregate计算每个plz分组的标准差(sd()),但如果某个分组只有1个数据点,标准差无法计算(单个数据无离散度),函数会返回NA,这就是d.Daten_Agg出现大量NA的核心原因。更关键的是:你的需求是展示各城镇所有数据点的箱线图,完全不需要提前聚合标准差——箱线图会自动基于原始数据计算四分位数、极值等统计量。
2. ggplot绘图错误的修正
- 第一个错误:
aes(y=d.Daten_Agg)是把整个数据框传给y轴映射,不符合ggplot语法,y轴需要指定数据集中的具体列; - 第二个错误:
ggplot(kk_agg, aes(y=kk_agg))中,kk_agg是d.Daten_Agg的列名,不是独立数据集,因此会报“对象未找到”; - 核心误区:误用聚合后的标准差数据绘制箱线图,箱线图的数据源应该是原始分组数据,而非聚合后的统计量。
修正后的代码
方案1:按plz分组绘制原始数据的箱线图(符合你的需求)
这是最贴合需求的方案,直接用原始数据集d.Daten绘图,自动按plz分组生成箱线图:
ggplot(d.Daten, aes(x = factor(plz), y = k_kehrricht)) + # 绘制箱线图的误差线 stat_boxplot(geom="errorbar", width=0.5) + # 绘制箱线图主体 geom_boxplot(fill="darkorchid3", outlier.color="darkorchid3", outlier.size=3, outlier.shape=8, width = 0.8) + # 设置坐标轴标签 ylab("Karton Kehrricht [kg]") + xlab("Postleitzahl (PLZ)") + # 标题样式 theme(plot.title = element_text(hjust = 0.5, margin = margin(t = 10), size = 12, vjust=2, face = "bold")) + # 若x轴PLZ标签过多,旋转45度避免重叠 theme(axis.text.x = element_text(angle = 45, hjust = 1))
方案2:若需保留聚合后的标准差数据(绘制标准差的箱线图)
如果确实需要基于标准差数据绘图,需先处理NA值(比如替换为0或过滤NA分组):
# 处理NA值:将标准差为NA的分组替换为0(也可根据需求用subset()过滤NA) d.Daten_Agg$kk_agg[is.na(d.Daten_Agg$kk_agg)] <- 0 # 绘制标准差的箱线图 ggplot(d.Daten_Agg, aes(y = kk_agg)) + stat_boxplot(geom="errorbar", width=0.5) + geom_boxplot(fill="darkorchid3", outlier.color="darkorchid3", outlier.size=3, outlier.shape=8, width = 1) + ylab("Standardabweichung Karton Kehrricht [kg]") + xlab("alle Daten") + scale_x_discrete() + theme(plot.title = element_text(hjust = 0.5, margin = margin(t = 10), size = 12, vjust=2, face = "bold"))
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

