如何忽略ggplot2箱线图中的异常值?我不是简单地希望它们消失(即outlier.size=0),而是希望它们被忽略,以便y轴缩放到显示第一/第三个百分位数。我的异常值导致“盒子”缩小到几乎成了一条线。有什么技术可以解决这个问题吗?
编辑示例如下:
y = c(.01, .02, .03, .04, .05, .06, .07, .08, .09, .5, -.6)
qplot(1, y, geom="boxplot")
发布于 2011-04-15 22:22:02
这是一个使用boxplot.stats的解决方案
# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]
# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)
发布于 2011-04-15 22:10:45
使用geom_boxplot(outlier.shape = NA)
不显示异常值,使用scale_y_continuous(limits = c(lower, upper))
更改轴限制。
举个例子。
n <- 1e4L
dfr <- data.frame(
y = exp(rlnorm(n)), #really right-skewed variable
f = gl(2, n / 2)
)
p <- ggplot(dfr, aes(f, y)) +
geom_boxplot()
p # big outlier causes quartiles to look too slim
p2 <- ggplot(dfr, aes(f, y)) +
geom_boxplot(outlier.shape = NA) +
scale_y_continuous(limits = quantile(dfr$y, c(0.1, 0.9)))
p2 # no outliers plotted, range shifted
实际上,正如Ramnath在他的答案中( Andrie也在评论中)所显示的那样,在计算完统计数据后,通过coord_cartesian
来裁剪比例更有意义。
coord_cartesian(ylim = quantile(dfr$y, c(0.1, 0.9)))
(您可能仍然需要使用scale_y_continuous
来修复轴中断。)
发布于 2012-09-20 18:50:52
我也有同样的问题,我使用boxplot.stats
预先计算了Q1,Q2,median,ymin,ymax的值
# Load package and generate data
library(ggplot2)
data <- rnorm(100)
# Compute boxplot statistics
stats <- boxplot.stats(data)$stats
df <- data.frame(x="label1", ymin=stats[1], lower=stats[2], middle=stats[3],
upper=stats[4], ymax=stats[5])
# Create plot
p <- ggplot(df, aes(x=x, lower=lower, upper=upper, middle=middle, ymin=ymin,
ymax=ymax)) +
geom_boxplot(stat="identity")
p
结果是一个没有异常值的箱线图。
https://stackoverflow.com/questions/5677885
复制相似问题