You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R分组箱线图中添加10%和90%分位数标记的技术需求

解决方案:绘制带10%/90%分位数的常规箱线图

你的核心需求是保留箱线图全部常规元素,同时额外标记10%和90%分位数。原代码的问题在于自定义函数替换了中位数为几何均值,且丢失了原箱线图的最小值、最大值和异常值展示。下面是直接可行的方案:

实现步骤

  1. 先用geom_boxplot()绘制标准箱线图,它默认会自动展示最小值、最大值、25%分位数、中位数(50%分位数)、75%分位数、异常值,完全满足常规元素要求。
  2. 再用stat_summary()添加10%和90%分位数的标记,这里用水平短线(也可以换成点)来区分。

完整可运行代码

# 加载ggplot2包(未安装先运行 install.packages("ggplot2"))
library(ggplot2)

# 你的数据集
dataset_stack <- structure(list(Col = c("Blue", "Blue", "Blue", "Blue", "Blue", 
                       "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", 
                       "Green", "Green", "Green", "Green", "Green", "Green", "Green", 
                       "Green", "Green", "Green", "Green", "Green", "Green", "Green", 
                       "Green", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", 
                       "Red", "Red", "Red", "Red", "Red", "Red", "Red"), TTC = c(0.9, 
                                                                                 0.7, 0, 0.1, 0.1, 0.4, 0.9, 0.8, 0.1, 0, 0.7, 0.2, 0.7, 0.2, 
                                                                                 0, 0.8, 0.7, 0.8, 0.9, 0.3, 0.9, 0.8, 0.3, 1, 0.6, 0.4, 0.3, 
                                                                                 0.3, 0.3, 0.2, 0.2, 0.7, 0.9, 0.9, 0.6, 0.4, 0.1, 0.4, 0.8, 0, 
                                                                                 0.7, 0.4, 0.7)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
                                                                                                                                                          -43L))

# 绘制图形
ggplot(dataset_stack, aes(x = Col, y = TTC)) +
  # 常规箱线图,保留所有默认元素
  geom_boxplot(width = 0.6) +
  # 添加10%和90%分位数的水平短线
  stat_summary(
    fun = function(x) quantile(x, c(0.1, 0.9), na.rm = TRUE),
    geom = "errorbar",
    width = 0.3,  # 短线宽度
    color = "red",  # 颜色区分
    size = 1
  ) +
  # 可选:如果想用点标记分位数,替换上面的stat_summary为下面这段
  # stat_summary(
  #   fun = function(x) quantile(x, c(0.1, 0.9), na.rm = TRUE),
  #   geom = "point",
  #   shape = 8,  # 星号形状
  #   color = "red",
  #   size = 2
  # ) +
  labs(title = "带10%/90%分位数的分组箱线图", x = "分组", y = "TTC") +
  theme_minimal()

代码说明

  • geom_boxplot():无需额外配置,自动生成你需要的所有常规箱线图元素。
  • stat_summary():通过自定义函数计算10%和90%分位数,用errorbar geom绘制水平短线,或者用point geom绘制标记点,颜色和大小可以按需调整。

内容的提问来源于stack exchange,提问作者CathiP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:42:39