Labeling Outliers of Boxplots in R
Asked Answered
I

6

26

I have the code that creates a boxplot, using ggplot in R, I want to label my outliers with the year and Battle.

Here is my code to create my boxplot

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

Can anyone help? I knew this is correct, I just want to label the outliers.

Isocline answered 4/11, 2015 at 14:41 Comment(2)
Where does data seabattle come from? Can you dput the data or provide sample data to make this example reproducible?Whitsunday
Anything you've already tried?Vinna
W
50

The following is a reproducible solution that uses dplyr and the built-in mtcars dataset.

Walking through the code: First, create a function, is_outlier that will return a boolean TRUE/FALSE if the value passed to it is an outlier. We then perform the "analysis/checking" and plot the data -- first we group_by our variable (cyl in this example, in your example, this would be PortugesOutcome) and we add a variable outlier in the call to mutate (if the drat variable is an outlier [note this corresponds to RatioPort2Dutch in your example], we will pass the drat value, otherwise we will return NA so that value is not plotted). Finally, we plot the results and plot the text values via geom_text and an aesthetic label equal to our new variable; in addition, we offset the text (slide it a bit to the right) with hjust so that we can see the values next to, rather than on top of, the outlier points.

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

Whitsunday answered 4/11, 2015 at 15:16 Comment(1)
quite useful, but just to add a warning: the helper function detects outlier correctly only if the variable (drat in this case ) is positive. For variables in a negative range q75<0 , and the formula leads to incorrect location of the upper outlier threshold. For q25 there isnt such problem.Hyperacidity
K
15

You can do this simply within ggplot itself, using an appropriate stat_summary call.

ggplot(mtcars, aes(x = factor(cyl), y = drat, fill = factor(cyl))) + 
  geom_boxplot() +
  stat_summary(
    aes(label = round(stat(y), 1)),
    geom = "text", 
    fun.y = function(y) { o <- boxplot.stats(y)$out; if(length(o) == 0) NA else o },
    hjust = -1
  )

enter image description here

Kakaaba answered 17/6, 2019 at 18:54 Comment(1)
How can I modify the aes call to label the outliers with some other variable, say mpg? I have tried calling aes(label = mpg) in stat_summary and the top ggplot call but I get an error saying geom_text requires a missing label aesthetic.Hudis
P
13

To label the outliers with rownames (based on JasonAizkalns answer)

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

Perbunan answered 27/4, 2017 at 13:57 Comment(0)
T
8

Similar answer to above, but gets outliers directly from ggplot2, thus avoiding any potential conflict in method:

# calculate boxplot object
g <- ggplot(mtcars, aes(factor(cyl), drat)) + geom_boxplot()

# get list of outliers 
out <- ggplot_build(g)[["data"]][[1]][["outliers"]]

# label list elements with factor levels
names(out) <- levels(factor(mtcars$cyl))

# convert to tidy data
tidyout <- purrr::map_df(out, tibble::as_tibble, .id = "cyl")

# plot boxplots with labels
g + geom_text(data = tidyout, aes(cyl, value, label = value), 
              hjust = -.3)

enter image description here

Taxiway answered 15/9, 2018 at 12:44 Comment(0)
V
7

Does this work for you?

library(ggplot2)
library(data.table)

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

ggplot defines an outlier by default as something that's > 1.5*IQR from the borders of the box.

#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

Vinna answered 4/11, 2015 at 15:12 Comment(0)
F
-2

With a small twist on @JasonAizkalns solution you can label outliers with their location in your data frame.

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

I load the data frame into the R Studio Environment, so I can then take a closer look at the data in outlier rows.

Fatidic answered 10/6, 2016 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.