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

如何在ggplotly中移除箱线图异常值但保留抖动点

在ggplotly中隐藏箱线图异常值的解决方法

由于ggplotly会重新计算箱线图的统计指标,导致ggplot中outlier.shape = NA的设置失效,以下是几种可行的解决方法:

方法1:手动计算箱线图统计量(推荐)

先手动计算箱线图所需的四分位数、上下须等统计量,再用stat="identity"绘制箱线图,让ggplotly直接沿用已计算好的数据,避免重新生成异常值点。

library(pacman)
pacman::p_load(dplyr, ggplot2, plotly)

# 计算箱线图统计量
box_stats <- chickwts %>%
  filter(feed == "sunflower") %>%
  summarize(
    ymin = quantile(weight, 0.25) - 1.5*IQR(weight),
    lower = quantile(weight, 0.25),
    middle = median(weight),
    upper = quantile(weight, 0.75),
    ymax = quantile(weight, 0.75) + 1.5*IQR(weight),
    feed = "sunflower"
  )

# 绘制箱线图+散点
g <- ggplot() +
  geom_boxplot(data = box_stats,
               aes(x = factor(feed), ymin = ymin, lower = lower, middle = middle, upper = upper, ymax = ymax, fill = factor(feed)),
               stat = "identity") +
  geom_jitter(data = chickwts %>% filter(feed == "sunflower"),
              aes(x = factor(feed), y = weight),
              alpha = 0.5, height = 0)

# 转换为ggplotly
ggplotly(g)

方法2:修改ggplotly的Trace参数

直接调整ggplotly生成的箱线图trace,将boxpoints参数设为"false",强制隐藏异常值。

library(pacman)
pacman::p_load(dplyr, ggplot2, plotly)

g <- ggplot(chickwts %>% filter(feed == "sunflower"),
            aes(x = factor(feed), y = weight, fill = factor(feed))) + 
  geom_boxplot(outlier.shape = NA) + 
  geom_jitter(alpha = 0.5, height = 0)

# 调整trace参数隐藏异常值
ggplotly(g) %>%
  style(boxpoints = "false", traces = 1)

注:若存在多个箱线图trace,需根据实际情况调整traces的序号,或用which函数定位目标trace。

方法3:结合ggplot参数与ggplotly调整

在ggplot中设置outlier.alpha = 0隐藏异常点,再配合ggplotly的参数确保异常值不被渲染:

g <- ggplot(chickwts %>% filter(feed == "sunflower"),
            aes(x = factor(feed), y = weight, fill = factor(feed))) + 
  geom_boxplot(outlier.alpha = 0) + 
  geom_jitter(alpha = 0.5, height = 0)

ggplotly(g) %>% style(boxpoints = "false", traces = 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:13:17