【问题标题】:Changing whisker length of multiple boxplot in R在R中改变多个箱线图的胡须长度
【发布时间】:2018-03-02 09:05:17
【问题描述】:

我有一个包含 10 个变量的数据框,并将其绘制成两列。但是ggplot 将胡须定义为第 5 和第 95 个百分位数。对于这些图和异常值,我希望像往常一样将晶须长度设为Q1 - 1.5*IQR / Q3 + 1.5*IQR。在link 中发布了一个类似的问题,但我无法使用它。任何帮助将不胜感激!

library(ggplot2)
library(tidyr)

df <- data.frame(matrix(rnorm(2000), ncol = 10))
plot.data <- gather(df, variable, value)
# plot.data$out <- as.numeric(rep(input_data, each = nrow(x_train)))
p <- ggplot(plot.data, aes(x = 0,  y=value))
p <- p + geom_boxplot()
#p <- p + geom_point(aes(x = 0, y = test_data), color = "red") 
p <- p + facet_wrap(~variable, scales = "free_x", strip.position = 'top', ncol = 2)
p <- p + coord_flip()
p <- p + xlab("") + ylab("")
p <- p + theme(legend.position="none") + theme_bw() 
p <- p + theme(axis.text.y=element_blank(),
          axis.ticks.y=element_blank())
p

【问题讨论】:

  • 您在帖子中找到的较低答案似乎很简单:stackoverflow.com/a/38504938/3124909

标签: r ggplot2 boxplot


【解决方案1】:

默认情况下(notched=FALSE),geom_boxplot() 应该为您提供所需的晶须(Q1 - 1.5*IQR / Q3 + 1.5*IQR)。查看更新的问题link。虽然,这受分位数 IQR 定义的影响。

如果您坚持使用 stat_summary 手动设置它们

# geom_boxplot parameters with stat summary
f <- function(x) {
  r <- quantile(x, probs = c(0.25, 0.25, 0.5, 0.75, 0.75))
  r[[1]]<-r[[1]]-1.5*IQR(x) #ymin lower whisker, as per geom_boxplot
  r[[5]]<-r[[5]]+1.5*IQR(x) #ymax upper whisker 
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax") 
  r 
}

# To subset the outlying points for plotting, 
o <- function(x) {
  r <- quantile(x, probs = c(0.25, 0.75))
  r[[1]]<-r[[1]]-1.5*IQR(x)
  r[[2]]<-r[[2]]+1.5*IQR(x)
  subset(x, x < r[[1]] | r[[2]] < x)
}

# added seed for consistency
set.seed(123)    

df <- data.frame(matrix(rnorm(2000), ncol = 10))
plot.data <- gather(df, variable, value)
# plot.data$out <- as.numeric(rep(input_data, each = nrow(x_train)))
p <- ggplot(plot.data, aes(x = 0,  y=value))
p <- p + stat_summary(fun.data = f, geom="boxplot")+ 
  stat_summary(fun.y = o, geom="point")
#p <- p + geom_point(aes(x = 0, y = test_data), color = "red") 
p <- p + facet_wrap(~variable, scales = "free_x", strip.position = 'top', ncol = 2)
p <- p + coord_flip()
p <- p + xlab("") + ylab("")
p <- p + theme(legend.position="none") + theme_bw() 
p <- p + theme(axis.text.y=element_blank(),
               axis.ticks.y=element_blank())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2015-01-11
    • 2014-03-26
    • 2012-07-26
    相关资源
    最近更新 更多