忽略ggplot2 boxplot中的exception值

我将如何忽略ggplot2 boxplot中的exception值? 我不只是希望他们消失(即outlier.size = 0),但我希望他们被忽略,这样的y轴缩放显示第1 /第3百分位。 我的exception值正在导致“盒子”缩小到几乎是一条线。 有没有一些技术来解决这个问题?

编辑这是一个例子:

y = c(.01, .02, .03, .04, .05, .06, .07, .08, .09, .5, -.6) qplot(1, y, geom="boxplot") 

在这里输入图像说明

这是一个使用boxplot.stats的解决scheme

 # 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) 

使用geom_boxplot(outlier.shape = NA)不显示exception值和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 

实际上,正如拉姆纳特在回答中所表明的那样(在评论中也是安德里),在通过coord_cartesian计算统计量之后,裁剪这些比例更有意义。

 coord_cartesian(ylim = quantile(dfr$y, c(0.1, 0.9))) 

(您可能仍然需要使用scale_y_continuous来修复轴断点。)

我有同样的问题,并使用boxplot.stats预先计算了Q1,Q2,median,ymin,ymax的boxplot.stats

 # 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 

结果是没有exception值的箱形图。 在这里输入图像说明

一个想法是用两遍程序来保存数据:

  1. 运行第一遍,了解界限是什么,例如在给定百分位数的情况下,或平均值以上的N标准偏差,或者…

  2. 在第二遍中,将超出给定界限的值设置为该界限的值

我应该强调,这是一种老式的方法,应该由更现代化的强大技术支配,但是你仍然会遇到很多。

 for( i in match(rownames(TT),rownames(data))){ File=paste('HNSC-',rownames(data)[i],".png",sep="") Name<-unlist(lapply(colnames(data),function(x) unlist(strsplit(x,"-TCGA"))[1])) type<-unlist(lapply(Name,function(x) unlist(strsplit(x,"-"))[2])) input<-data.frame(lncRNA=as.numeric(as.character(data[i,])),Name,type) p<-ggplot(input,aes(Name,lncRNA,fill=factor(type))) p<-p+geom_boxplot(outlier.shape=NA) max<-max(tapply(input$lncRNA,input$Name,function(x) quantile(x,0.975))) min<-min(tapply(input$lncRNA,input$Name,function(x) quantile(x,0))) p<-p+coord_flip(ylim = c(min, max)) p ggsave(File) } 

geom_boxplot函数的“coef”选项允许根据四分位间距改变exception值截止值。 这个选项是为stat_boxplot函数logging的。 要取消exception值(换句话说,它们被视为常规数据),可以不使用默认值1.5来指定非常高的截止值:

 library(ggplot2) # generate data with outliers: df = data.frame(x=1, y = c(-10, rnorm(100), 10)) # generate plot with increased cutoff for outliers: ggplot(df, aes(x, y)) + geom_boxplot(coef=1e30)