2015-11-04 70 views
8

我有创建boxplot的代码,在R中使用ggplot,我想用年度和战斗标记我的异常值。在R中标注Boxlot的异常值

这里是我的代码来创建我的箱线图

require(ggplot2) 
ggplot(seabattle, aes(x=PortugesOutcome,y=RatioPort2Dutch),xlim="OutCome", 
y="Ratio of Portuguese to Dutch/British ships") + 
geom_boxplot(outlier.size=2,outlier.colour="green") + 
stat_summary(fun.y="mean", geom = "point", shape=23, size =3, fill="pink") + 
ggtitle("Portugese Sea Battles") 

谁能帮助?我知道这是正确的,我只想标出异常值。

+2

哪里数据'seabattle'从何而来?你能输入数据还是提供样本数据,以使这个例子具有可重现性? – JasonAizkalns

+0

你有没有试过? – Heroka

回答

5

这是否适合您?

library(ggplot2) 
library(data.table) 

#generate some data 
set.seed(123) 
n=500 
dat <- data.table(group=c("A","B"),value=rnorm(n)) 

ggplot默认定义了一个异常值,它是框的边界上大于1.5 * IQR的值。

#function that takes in vector of data and a coefficient, 
#returns boolean vector if a certain point is an outlier or not 
check_outlier <- function(v, coef=1.5){ 
    quantiles <- quantile(v,probs=c(0.25,0.75)) 
    IQR <- quantiles[2]-quantiles[1] 
    res <- v < (quantiles[1]-coef*IQR)|v > (quantiles[2]+coef*IQR) 
    return(res) 
} 

#apply this to our data 
dat[,outlier:=check_outlier(value),by=group] 
dat[,label:=ifelse(outlier,"label","")] 

#plot 
ggplot(dat,aes(x=group,y=value))+geom_boxplot()+geom_text(aes(label=label),hjust=-0.3) 

enter image description here

10

下面是使用dplyr可再现溶液和内置mtcars数据集。

遍历代码:首先,创建一个函数is_outlier,如果传递给它的值是异常值,则返回布尔值TRUE/FALSE。然后,我们执行“分析/检查”并绘制数据 - 首先我们的变量group_by我们的变量(在本例中为cyl,在您的示例中为PortugesOutcome),我们在调用mutate时添加变量outlier(如果drat变量是一个异常值[请注意,在本例中对应于RatioPort2Dutch],我们将传递drat值,否则我们将返回NA,以便不绘制值)。最后,我们绘制结果并通过geom_text绘制文本值,并将审美标签等于我们的新变量;此外,我们用hjust抵消了文本(向右滑动一点),以便我们可以看到离群点旁边的值,而不是离群点的顶部值。

library(dplyr) 
library(ggplot2) 

is_outlier <- function(x) { 
    return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x)) 
} 

mtcars %>% 
    group_by(cyl) %>% 
    mutate(outlier = ifelse(is_outlier(drat), drat, as.numeric(NA))) %>% 
    ggplot(., aes(x = factor(cyl), y = drat)) + 
    geom_boxplot() + 
    geom_text(aes(label = outlier), na.rm = TRUE, hjust = -0.3) 

Boxplot

-2

随着@JasonAizkalns解决方案可以标记离群与他们在数据帧的位置一小搓。

mtcars[,'row'] <- row(mtcars)[,1] 
... 
mutate(outlier = ifelse(is_outlier(drat), row, as.numeric(NA))) 
... 

我将数据框加载到R Studio环境中,然后我可以仔细看看异常行中的数据。

2

为了标记离群值rownames(基于JasonAizkalns答案)

library(dplyr) 
library(ggplot2) 
library(tibble) 

is_outlier <- function(x) { 
    return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x)) 
} 

dat <- mtcars %>% tibble::rownames_to_column(var="outlier") %>% group_by(cyl) %>% mutate(is_outlier=ifelse(is_outlier(drat), drat, as.numeric(NA))) 
dat$outlier[which(is.na(dat$is_outlier))] <- as.numeric(NA) 

ggplot(dat, aes(y=drat, x=factor(cyl))) + geom_boxplot() + geom_text(aes(label=outlier),na.rm=TRUE,nudge_y=0.05) 

boxplot with outliers name