如何用ggplot绘制自定义中位数与范围的多箱线图?
问题:自定义箱线图中位数与范围的ggplot代码修正
我希望在一张图表中绘制自定义中位数与数值范围的箱线图,但当前ggplot代码生成的图表不符合预期。目标是每个类别对应一个箱线图,且箱线的最小值、下四分位、中位数、上四分位、最大值都由数据框中指定的列控制。
现有问题代码
ggplot(data = df_subset[df, aes(y = target_fed_funds_rate_median, x = Date, group = Date)) + geom_boxplot(aes(ymin = target_fed_funds_rate_lr, lower = target_fed_funds_rate_cl, middle = target_fed_funds_rate_median, upper = target_fed_funds_rate_ch, ymax = target_fed_funds_rate_hr))
可复现代码
time = c(1, 2, 3, 4, 5) median = c(1, 2, 3, 4, 5) low = c(0.5, 1.5, 2.5, 3.5, 4.5) high = c(1.5, 2.5, 3.5, 4.5, 5.5) center_high = c(1.25, 2.25, 3.25, 4.25, 5.25) center_low = c(0.75, 1.75, 2.75, 3.75, 4.75) df = data.frame(median, low, high, center_high, center_low) ggplot(data = df, aes(y = median, x = time, group = time)) + geom_boxplot(aes(ymin = low, lower = center_low, middle = median, upper = center_high, ymax = high))
修正方案
问题核心是geom_boxplot默认会自动计算统计量,覆盖手动指定的参数值,需添加stat = "identity"强制使用自定义统计量。
修正后的可复现代码
time = c(1, 2, 3, 4, 5) median = c(1, 2, 3, 4, 5) low = c(0.5, 1.5, 2.5, 3.5, 4.5) high = c(1.5, 2.5, 3.5, 4.5, 5.5) center_high = c(1.25, 2.25, 3.25, 4.25, 5.25) center_low = c(0.75, 1.75, 2.75, 3.75, 4.75) df = data.frame(median, low, high, center_high, center_low) ggplot(data = df, aes(x = factor(time), group = time)) + geom_boxplot( aes( ymin = low, lower = center_low, middle = median, upper = center_high, ymax = high ), stat = "identity" # 关键:使用手动指定的统计量,不自动计算 ) + labs(x = "time", y = "value")
针对原始数据的修正代码
# 修正语法错误+添加stat参数 ggplot(data = df_subset, aes(x = Date, group = Date)) + geom_boxplot( aes( ymin = target_fed_funds_rate_lr, lower = target_fed_funds_rate_cl, middle = target_fed_funds_rate_median, upper = target_fed_funds_rate_ch, ymax = target_fed_funds_rate_hr ), stat = "identity" )
额外说明
stat = "identity"是必须项:告诉ggplot直接使用提供的ymin/lower/middle/upper/ymax列值,而非自动计算- 原始代码中
df_subset[df是语法错误,需直接使用df_subset作为数据源 - 若
x轴变量是数值型(如示例中的time),转为因子factor(time)可让每个类别对应独立箱线,布局更符合预期
内容的提问来源于stack exchange,提问作者TRV
相关产品推荐
相关产品推荐

