有人能向我解释为什么我得到不同数量的outliers
与正常箱线图命令,并与geom_boxplot
中GGPLOT2?这里有一个例子:
x <- c(280.9, 135.9, 321.4, 333.7, 0.2, 71.3, 33.0, 102.6, 126.8, 194.8, 35.5,
107.3, 45.1, 107.2, 55.2, 28.1, 36.9, 24.3, 68.7, 163.5, 0.8, 31.8, 121.4,
84.7, 34.3, 25.2, 101.4, 203.2, 194.1, 27.9, 42.5, 47.0, 85.1, 90.4, 103.8,
45.1, 94.0, 36.0, 60.9, 97.1, 42.5, 96.4, 58.4, 174.0, 173.2, 164.1, 92.1,
41.9, 130.2, 94.7, 121.5, 261.4, 46.7, 16.3, 50.7, 112.9, 112.2, 242.5, 140.6,
112.6, 31.2, 36.7, 97.4, 140.5, 123.5, 42.9, 59.4, 94.5, 37.4, 232.2, 114.6,
60.7, 27.8, 115.5, 111.9, 60.1)
data <- data.frame(x)
boxplot(data$x)
ggplot(data, aes(y=x)) + geom_boxplot()
用boxplot
命令我得到下面的图4 outliers
.
随着ggplot2
我得到下面的情节5 outliers
.
1> dww..:
ggplot和boxplot使用略有不同的方法来计算统计数据.从?geom_boxplot
我们可以看出
下铰链和上铰链对应于第一和第三四分位数(第25和第75百分位数).这与boxplot()函数使用的方法略有不同,对于小样本可能很明显.有关如何计算boxplot()的铰链位置的更多信息,请参见boxplot.stats().
boxplot.stats
如果你想要相同的结果,你可以使用ggplot
# Function to use boxplot.stats to set the box-and-whisker locations
f.bxp = function(x) {
bxp = boxplot.stats(x)[["stats"]]
names(bxp) = c("ymin","lower", "middle","upper","ymax")
bxp
}
# Function to use boxplot.stats for the outliers
f.out = function(x) {
data.frame(y=boxplot.stats(x)[["out"]])
}
要在ggplot中使用这些函数:
ggplot(data, aes(0, y=x)) +
stat_summary(fun.data=f.bxp, geom="boxplot") +
stat_summary(fun.data=f.out, geom="point")
如果要复制ggplot本机使用的统计信息,请按以下说明进行?geom_boxplot
说明:
ymin =较低的晶须=最大观察值大于或等于较低的铰链 - 1.5*IQR
lower =下铰链,25%分位数
缺口低点 =缺口下缘=中位数 - 1.58*IQR/sqrt(n)
中 =中位数,50%分位数
notchupper =陷波的上边缘=中位数+ 1.58*IQR/sqrt(n)
上部 =上部铰链,75%分位数
ymax =上部晶须=小于或等于上部铰链的最大观察值+ 1.5*IQR
我们可以相应地计算出来:
y = sort(x)
iqr = quantile(y,0.75) - quantile(y,0.25)
ymin = y[which(y >= quantile(y,0.25) - 1.5*iqr)][1]
ymax = tail(y[which(y <= quantile(y,0.75) + 1.5*iqr)],1)
lower = quantile(y,0.25)
upper = quantile(y,0.75)
middle = quantile(y,0.5)
ggplot(data, aes(y=x)) +
geom_boxplot() +
geom_hline(aes(yintercept=c(ymin)), color='red', linetype='dashed') +
geom_hline(aes(yintercept=c(ymax)), color='red', linetype='dashed') +
geom_hline(aes(yintercept=c(lower)), color='red', linetype='dashed') +
geom_hline(aes(yintercept=c(upper)), color='red', linetype='dashed') +
geom_hline(aes(yintercept=c(middle)), color='red', linetype='dashed')
我们也可以直接从ggplot对象中提取这些统计信息 ggplot_build
p <- ggplot(data, aes(y=x)) + geom_boxplot()
ggplot_build(p)$data[1:5]
# ymin lower middle upper ymax
# 1 0.2 42.5 93.05 122 232.2