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

如何用ggplot2保留箱线图的中位数与须线并移除箱体

用ggplot2实现仅保留中位数与须线的箱线图(移除箱体)

需求说明

需要移除箱线图的箱体部分,仅保留中位数线和须线,同时希望须线能延伸至中位数位置。


方案1:基于标准箱线图参数隐藏箱体

直接通过geom_boxplot的参数控制,隐藏箱体的填充与边框,只保留中位数和须线:

library(ggplot2)

ggplot(InsectSprays, aes(x = spray, y = count)) +
  # 核心:隐藏箱体,保留中位数和须线
  geom_boxplot(
    fill = NA,          # 取消箱体填充色
    colour = NA,        # 取消箱体边框
    median.colour = "black", # 中位数线颜色
    median.size = 1.2,  # 中位数线粗细
    whisker.colour = "black", # 须线颜色
    whisker.size = 1,   # 须线粗细
    width = 0.5         # 中位数线的宽度
  ) +
  # 保留原需求的抖动散点
  geom_jitter(
    aes(fill = spray),
    shape = 21,
    color = "black",
    size = 5,
    alpha = 0.8 # 可选:降低透明度减少散点重叠
  ) +
  # 原需求的主题设置
  theme_bw() +
  theme(
    axis.line = element_line(color = 'black'),
    plot.background = element_blank(),
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(),
    legend.position = "none"
  ) +
  labs(y = "Counts")

方案2:须线直接延伸至中位数(自定义统计量)

如果需要须线从最小值直接连到最大值,同时中位数线横跨须线(即须线与中位数线完全连接),可以用stat_summary手动计算统计量并绘制:

library(ggplot2)

ggplot(InsectSprays, aes(x = spray, y = count)) +
  # 绘制从最小值到最大值的竖线(须线)+ 中位数横线
  stat_summary(
    fun.data = function(x) {
      data.frame(
        ymin = min(x),   # 最小值(须线下端点)
        ymax = max(x),   # 最大值(须线上端点)
        y = median(x)    # 中位数位置
      )
    },
    geom = "crossbar",   # 用crossbar实现竖线+横线的组合
    width = 0.5,         # 中位数横线的宽度
    fill = NA,
    colour = "black",
    size = 1
  ) +
  # 抖动散点(同方案1)
  geom_jitter(
    aes(fill = spray),
    shape = 21,
    color = "black",
    size = 5,
    alpha = 0.8
  ) +
  # 主题设置(同方案1)
  theme_bw() +
  theme(
    axis.line = element_line(color = 'black'),
    plot.background = element_blank(),
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(),
    legend.position = "none"
  ) +
  labs(y = "Counts")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:12:10