如何在 R 中创建具有不同字符的箱线图以识别中度和极端异常值?
How to create a boxplot in R with different characters to identify moderate and extreme outliers?
我想在 R 中创建一个具有中等 (o; <= Q1-1.5IQR; >= Q3+1.5IQR) 和 extreme/severe (*; <= Q1-3IQR; >= Q3+3IQR) 异常值识别不同。像这样:
一种方法是更改 range
参数并在第一个箱线图之上添加另一个箱线图。但是很难抑制特定的离群值,所以我没有用 * 表示极端离群值,而是用 pch
=20.
填充了默认的 O (pch
=1)
set.seed(1)
x <- rt(200, df=3)
boxplot(x, outcol="red")
boxplot(x, add=TRUE, range=3, pars=list(outpch=20, outcol="red", whisklty=0, staplelty=0))
如果你真的想要星号,你可以把它们做得更大,这样它们就完全遮住了之前的圆圈(中等异常值)。
boxplot(x, outcol="red")
boxplot(x, add=TRUE, range=3,
pars=list(outpch='*', outcol="red", outcex=3, whisklty=0, staplelty=0))
我实现了一个优雅的解决方案:
y <- c(-4,3,3,3,4,4,5,6,7,8,12,16,26)
par(bty = 'n',mar = c(0,2,0,0))
bp <-boxplot(x = y, plot=FALSE,ylab="x",mgp = c(3, 3, 0),axes=FALSE)
#ii) Plot the boxplot, suppressing points with outpch=NA.
bxp(bp, outpch=NA)
bxp.extreme<-function(z, extreme=3.5) {
boxrange <- bp$stats[4,bp$group] - bp$stats[2,bp$group]
big.outlier<- (z$out >= bp$stats[4,bp$group] + extreme*boxrange) |
(z$out <= bp$stats[2,bp$group] - extreme*boxrange)
return(big.outlier)
}
ext<-bxp.extreme(bp)
points(bp$group, bp$out, pch=ifelse(ext, 8,1), col=ifelse(ext, 1,1))
legend(title = "Outliers","topright", bty="0", legend=c(expression(atop("Q"[1]*"-1.5IQR ≤ Moderate ≤ Q"[3]*"-3IQR","Q"[3]*"+1.5IQR ≤ Moderate ≤ Q"[3]*"+3IQR")),
expression(atop("Extreme ≤ Q"[1]*"-3IQR","Extreme ≥ Q"[3]*"+3IQR"))),
pch=c(1,8), col=c(1,1),y.intersp=1.5)
我使用找到的代码 here 并对其进行了改编。
我想在 R 中创建一个具有中等 (o; <= Q1-1.5IQR; >= Q3+1.5IQR) 和 extreme/severe (*; <= Q1-3IQR; >= Q3+3IQR) 异常值识别不同。像这样:
一种方法是更改 range
参数并在第一个箱线图之上添加另一个箱线图。但是很难抑制特定的离群值,所以我没有用 * 表示极端离群值,而是用 pch
=20.
pch
=1)
set.seed(1)
x <- rt(200, df=3)
boxplot(x, outcol="red")
boxplot(x, add=TRUE, range=3, pars=list(outpch=20, outcol="red", whisklty=0, staplelty=0))
如果你真的想要星号,你可以把它们做得更大,这样它们就完全遮住了之前的圆圈(中等异常值)。
boxplot(x, outcol="red")
boxplot(x, add=TRUE, range=3,
pars=list(outpch='*', outcol="red", outcex=3, whisklty=0, staplelty=0))
我实现了一个优雅的解决方案:
y <- c(-4,3,3,3,4,4,5,6,7,8,12,16,26)
par(bty = 'n',mar = c(0,2,0,0))
bp <-boxplot(x = y, plot=FALSE,ylab="x",mgp = c(3, 3, 0),axes=FALSE)
#ii) Plot the boxplot, suppressing points with outpch=NA.
bxp(bp, outpch=NA)
bxp.extreme<-function(z, extreme=3.5) {
boxrange <- bp$stats[4,bp$group] - bp$stats[2,bp$group]
big.outlier<- (z$out >= bp$stats[4,bp$group] + extreme*boxrange) |
(z$out <= bp$stats[2,bp$group] - extreme*boxrange)
return(big.outlier)
}
ext<-bxp.extreme(bp)
points(bp$group, bp$out, pch=ifelse(ext, 8,1), col=ifelse(ext, 1,1))
legend(title = "Outliers","topright", bty="0", legend=c(expression(atop("Q"[1]*"-1.5IQR ≤ Moderate ≤ Q"[3]*"-3IQR","Q"[3]*"+1.5IQR ≤ Moderate ≤ Q"[3]*"+3IQR")),
expression(atop("Extreme ≤ Q"[1]*"-3IQR","Extreme ≥ Q"[3]*"+3IQR"))),
pch=c(1,8), col=c(1,1),y.intersp=1.5)
我使用找到的代码 here 并对其进行了改编。