Skip to main content

1  Introduction

Data analysis is about finding the stories hidden in the mass of information that makes up a data set. Usually we are interested in understanding the major patterns — the relationships that hold true for most of the data. But sometimes we need to look at the weird observations — those that don’t follow the crowd and behave differently. These weird observations are the “anomalies”. They are the mavericks in the data, and in this book, they are what we find interesting.

Anomalies are often a nuisance. For example, they may be simply recording errors that are contaminating our data. We want to find them, remove them, and get on with analysing the bulk of the data. At other times, anomalies are the observations we care about. They tell us things that might otherwise go unnoticed if we only consider how the majority of observations behave. Whether we want to remove them or study them, we first need to find them.

1.1 Definitions

An anomaly is an observation that behaves differently from the bulk of the data. Anomalies are also called “outliers”, “novelties”, “deviants”, “abnormalities” or “discordants”. I prefer to use “anomalies” as it is a more general term than “outliers”, and it is more widely used than the other options.

An old definition due to Barnett & Lewis (1994) states

an outlier in a set of data [is] an observation (or subset of observations) which appears to be inconsistent with the remainder of that set of data.

Hawkins (1980) defined it like this:

An outlier is an observation which deviates so much from the other observations as to arouse suspicions that it was generated by a different mechanism.

These definitions are too vague to be useful, so we will need to be more specific. Following Hyndman & Frazier (2026), an anomaly is defined as an observation that has very low probability of occurring under some assumed probability distribution. This definition is more useful, as it allows us to use probability theory to identify and study anomalies. However, it raises two immediate questions:

  1. What probability distribution should we use? This depends on the application, and the nature of the data. In practice, we will often have to estimate the distribution from the available observations, which leads to further complications. Even if we think we know the underlying distribution, we may be wrong. So this book aims to use methods that reliably identify anomalies, even if the assumed distribution is mis-specified.
  2. What is meant by “very low”? Again, it is application-dependent, and we will need to set an appropriate threshold probability for determining what we consider to be an anomaly.

I will sometimes use the term outlier to mean an anomaly that lies at the outer edges of a data set. In contrast, inliers are anomalies that occur in unlikely regions, but not at the extremes. Some papers and books use the term “inlier” to denote any point that is not an outlier. However, this book uses the earlier definition of “inlier”, meaning an anomaly that is not an outlier.

Rejecting anomalies

Many analysts have thrown away apparent anomalies because they were assumed to be errors. There are even formal statistical tests to tell you which observations should be ignored. In my view, this is a dangerous practice. No anomalies should be removed unless you understand what led to their unusual behaviour in the first place. Often the most interesting observations are the ones that appear anomalous. They are the ones that tell us something new and unexpected, so we should not be too quick to reject them.

Sometimes we may want to use methods that are robust to anomalies, so that we can ignore them without worrying about their effect on the analysis. But this is not the same as removing them. Even when we use robust methods, it is still worth investigating any observations that appear anomalous, in order to fully understand the variation in the data.

How NASA didn’t discover the hole in the ozone layer

There is a widespread myth that NASA did not discover the hole in the ozone layer above the Antarctic because they had been throwing away anomalous data that would have revealed it. This is not true, but the real story is also instructive (Christie, 2001, 2004; Pukelsheim, 1990).

The “ozone hole” refers to low levels of ozone in the atmosphere above Antarctica and surrounding areas. NASA has been collecting satellite data on Antarctic ozone levels since 1979, initially using a Total Ozone Mapping Spectrometer (TOMS), while British scientists have collected ozone data using ground sensors at the Halley Research Station, on the edge of the Brunt Ice Shelf in Antarctica, since 1957. Figure 1.1 shows mean daily values for October from the NASA measurements in blue, and from the British observations in orange. There is a clear downward trend in the British data, especially from the late 1970s, which is confirmed with the NASA data. So why wasn’t the “ozone hole” discovered until 1985?

Code
tmp <- readr::read_csv(
  "https://OTexts.com/weird/data/halley_toms_ozone.txt",
  skip = 2
) |>
  rename(
    Year = "#   year",
    Instrument = "instrument",
    Ozone = "ozone"
  )
ozone <- bind_rows(
  tmp |>
    filter(!is.na(Instrument)),
  tmp |>
    filter(is.na(Instrument), !stringr::str_detect(Year, "^#")) |>
    mutate(Instrument = "Halley")
) |>
  mutate(
    Year = readr::parse_integer(Year),
    Ozone = readr::parse_number(Ozone)
  )
ozone |>
  filter(Instrument %in% c("Halley", "TOMS")) |>
  ggplot(aes(x = Year, y = Ozone, colour = Instrument)) +
  geom_point() +
  geom_hline(aes(yintercept = 180), col = "grey") +
  labs(y = "Total Ozone (DU)") +
  scale_y_continuous(sec.axis = dup_axis(breaks = 180, name = ""))
Figure 1.1: Observations of Antarctic ozone levels since 1957, measured in Dobson units (DU). Observations are mean daily values from October each year. Ground observations are from Halley Research Station, while satellite observations were obtained using a Total Ozone Mapping Spectrometer (TOMS). The satellite data were obtained from Leslie R Lait (NASA), while the Halley ground observations were obtained from Jonathan Shanklin (British Antarctic Survey). The horizontal line shows the threshold of 180 DU, used by NASA to determine when the ozone level was unusually low.

The British scientists had noticed the low ozone values as early as 1981, but it took a few years for the scientists to be convinced that the low values were real and not due to instrument problems, and then there were the usual publication delays. Eventually, the results were published in Farman et al. (1985).

Meanwhile, NASA was flagging observations as anomalous when they were below 180 DU (shown as a horizontal line in Figure 1.1). As is clear from the figure, this is much lower than any of the plotted points before the early 1980s. However, the 180 threshold was used for the daily measurements, which are much more variable than the monthly averages that are plotted. Occasionally daily observations did fall below 180, and so it was a reasonable threshold for the purpose of identifying instrument problems.

In fact, NASA had checked the unusually low TOMS values obtained before 1985 by comparing them against other available data. But the other data available to them showed ozone values of about 300 DU, so it was assumed that the satellite sensor was malfunctioning. The British Halley data were not available to them, and only after the publication of Farman et al. (1985) did the NASA scientists realise that the TOMS results were accurate.

In 1986, NASA scientists were able to confirm the British finding, also demonstrating that the ozone hole was widespread across the Antarctic (Stolarski et al., 1986).

This example reveals some lessons about anomaly detection:

  • The NASA threshold of 180 was based on daily data, and was designed to identify instrument problems, not genuine systematic changes in ozone levels. The implicit assumption was that ozone levels varied seasonally, but that otherwise the distribution of observations was stable. All anomaly detection involves some assumptions like this, and it is well to be aware of them. I will aim to make such assumptions explicit in this book.
  • Sometimes what we think are anomalies are not really anomalies, but the result of incorrect assumptions.
  • Often smoothing or averaging data will help to reveal issues that are not so obvious from the original data. This reduces the variation in the data, and allows more systematic variation to be uncovered.
  • Always plot the data. In this case, a graph such as Figure 1.1 would have revealed the problem in the late 1970s, but it seems no-one was producing plots like this.

As this episode illustrates, anomaly detection is inseparable from the context, and from the assumptions we make about stability and variability.

1.2 Approaches to anomaly detection

Some anomaly detection methods estimate how likely each observation is under a probability distribution; others measure how far, or how easily isolated, each observation is from the rest of the data, without an explicit probability model. This book covers both, but favours the probabilistic perspective, because it leads to anomaly scores that can be interpreted as probabilities, and so to natural thresholds for deciding when an observation is anomalous. Consequently, Chapter 2 and Chapter 3 introduce (or revise) some material on probability distributions and related tools.

Z-scores and statistical tests

The early days of anomaly detection involved methods based on statistical tests. Typically, the data were assumed to come from some underlying probability distribution, and then observations were declared outliers if they appeared to be inconsistent with this assumption. By far the most popular of these methods are based on the Normal distribution and use z-scores. Even today, such methods are extremely widely used. These are discussed in Chapter 4.

Boxplot methods

The second half of the 20th century witnessed the advent of computing, which allowed more sophisticated exploratory data analysis to be developed, including boxplots. Most readers will be familiar with boxplots, which provide a simple and effective way to visualise the distribution of a variable, and are often also used for anomaly detection. Such methods are discussed in Chapter 5.

Distance- and density-based methods

Modern tools for anomaly detection can be roughly divided into two groups: those based on densities and those based on distances. Distance-based tools usually compute the pairwise distances between observations and identify anomalies as those points that are far from other points. Density-based tools compute the probability density at each observation and identify anomalies as those points with very low density. The two ideas are closely related because density estimates are often based on distances; for example, a density estimate at a point may be a function of the distances between that point and all other observations. Conversely, distance-based tools are making an implicit assumption about the probability distribution of the data, and how likely it is to find points at different distances from other observations.

Distance-based methods are discussed in Chapter 6, while density-based methods are the subject of Chapter 7.

Regression methods

Sometimes we are interested in anomalies in one variable of interest (the “response”), after allowing for the values of some other variables (the “predictors”). For example, we might want to find wines that are unusually expensive given how highly they were rated by reviewers. Then an anomaly is an observation whose response is unusual given its predictor values, rather than one that is unusual in itself. Such methods are discussed in Chapter 8.

Beyond simple data sets

For the most part, the methods in Chapter 4 to Chapter 8 are illustrated using numerical data with only one or two variables. This makes it possible to introduce the main ideas and tools of anomaly detection in a simple setting, where we can easily visualise the data and the anomalies. However, many real data sets are more complex than this, and we will need to use more sophisticated methods to find anomalies in them.

Chapter 9 discusses methods for finding anomalies in high-dimensional data, where there are many variables (sometimes more variables than observations).

The remaining chapters of the book discuss applications of these methods to different types of data, including categorical data (Chapter 10), text (Chapter 11), time series (Chapter 12), functional data (Chapter 13), image data (Chapter 14), data which are probability distributions (Chapter 15), network data (Chapter 16), and event and log data (Chapter 17).

Statistical vs machine learning approaches

Anomaly detection has a long history in the statistics literature, including all the approaches developed in the 20th century, and many of the newer density-based approaches.

Recently, computer scientists have turned their attention to the problem of anomaly detection, especially as data sets have grown in size and complexity. Anomaly detection arises in cyber-security systems (where intrusions are identified as anomalies), in credit-card fraud (where unusual buying patterns are anomalous) and in remote sensing (where unusual changes in land use are anomalies). Machine learning approaches have been developed to address these problems, mostly using distance-based methods, although some important contributions to the density-based methods have also appeared in the machine learning literature.

In this book, I make no attempt to distinguish methods as “statistical” or “machine learning”. The distinction is largely about the training of the researchers, or the journals in which they publish; it has little to do with the methods themselves. In any case, the two communities have been slowly moving closer together, with computer scientists taking a more probabilistic perspective than previously, and statisticians taking a more computational and algorithmic approach than their forebears. Now there is considerable interaction and overlap between these communities, and continuing to label methods as “statistical” or “machine learning” is unhelpful.

Supervised vs unsupervised approaches

Some books and papers distinguish “supervised anomaly detection” from “unsupervised anomaly detection”. In the former case, anomalies are identified using human input, and then a model or algorithm is employed to learn how to identify new anomalies contained within new data. I do not regard this as anomaly detection, and I do not cover it in this book. It is possible, for example, that what a human labels as “anomalous” is not anomalous in a statistical sense. What is called “supervised anomaly detection” is actually a classification problem, where the aim is to mimic the human who labelled the training set. In that case, different tools are employed.

This book considers only unsupervised problems. That is, we have no idea a priori which observations are anomalous, and there is no “right” answer when it comes to real data.

Testing anomaly detection algorithms

The lack of a right answer makes it difficult to measure how well an anomaly detection algorithm performs. If we don’t know the right answer, we can’t know if an algorithm has found the true anomalies. There are three solutions to this problem that are often employed when testing anomaly detection algorithms.

  1. Synthetic data: We can use synthetic data that have been deliberately contaminated with a few known anomalies. This approach allows us to study the sensitivity of an algorithm to anomalies — how anomalous does an observation have to be before it is detected? A drawback to this approach is that synthetic data are often simpler and neater than real data, making the anomaly detection task easier than it is in reality.
  2. Human labelled: We can use real data where a human has labelled some of the observations as anomalous. As noted above, this only works when the human has correctly and completely labelled the anomalies. It also requires that what a human considers an anomaly is also anomalous in a statistical sense.
  3. Downsampled category: We can use real data that contain a categorical variable taking two label values. One of the labelled categories is downsampled and the corresponding observations form the anomalous subset. This approach is useful in obtaining large sets of realistic data, as it takes little time to create the data set. However, it requires that the observations labelled anomalies are different in some way from the other observations (apart from their label).

In this book, we will use data sets of each type when testing different anomaly detection methods. Section 1.4 describes the main data sets used in the chapters that follow.

1.3 Spurious anomalies and undetected anomalies

Spurious anomalies occur when a non-anomalous observation is identified as anomalous, while undetected anomalies occur when an anomalous observation is not detected. Thus, when our purpose is anomaly detection, an undetected anomaly is a “false negative” while a spurious anomaly is a “false positive”. We can only really be sure about which observations are spurious or undetected anomalies when the data are synthetic. However, some real data examples contain anomalies so extreme that they can safely be treated as true anomalies.

In some applications, we will be less interested in detecting anomalies than in ranking observations according to their degree of “anomalousness”. For example, we may have a limited team of human analysts who can investigate a few observations, and we want to make sure that they investigate the most anomalous observations. Then it is important to compute an anomaly score, so we can rank the observations according to their scores, and our analysts can look at the observations with the highest scores.

In fact, anomaly scores often underpin the algorithms that are used to detect anomalies. The algorithms compute a score for each observation, and then identify the observations with scores above some threshold as the anomalies. So anomaly scores appear throughout this book, even where the aim is to detect anomalies.

1.4 Data sets

Test cricket batting data

Cricket is a popular sport in England, India, Australia, and other countries which had strong ties to England during the 19th and 20th centuries. The cricket_batting data set contains summary statistics for all 3968 men and women who have played Test cricket (the traditional and long form of the game), up to 6 October 2025. Each row contains data on one player, and we will be looking for anomalies in their playing statistics.

cricket_batting
# A tibble: 3,968 × 15
   Player    Country Start   End Matches Innings NotOuts  Runs HighScore HighScoreNotOut
   <chr>     <chr>   <int> <int>   <int>   <int>   <int> <int>     <int> <lgl>          
 1 BB Cooper Austra…  1877  1877       1       2       0    18        15 FALSE          
 2 C Banner… Austra…  1877  1879       3       6       2   239       165 TRUE           
 3 DW Grego… Austra…  1877  1879       3       5       2    60        43 FALSE          
 4 EJ Grego… Austra…  1877  1877       1       2       0    11        11 FALSE          
 5 FR Spoff… Austra…  1877  1887      18      29       6   217        50 FALSE          
 6 JM Black… Austra…  1877  1894      35      62      11   800        74 FALSE          
 7 JR Hodges Austra…  1877  1877       2       4       1    10         8 FALSE          
 8 NFD Thom… Austra…  1877  1877       2       4       0    67        41 FALSE          
 9 TJD Kelly Austra…  1877  1879       2       3       0    64        35 FALSE          
10 TK Kenda… Austra…  1877  1877       2       4       1    39        17 TRUE           
# ℹ 3,958 more rows
# ℹ 5 more variables: Average <dbl>, Hundreds <int>, Fifties <int>, Ducks <int>,
#   Gender <chr>

Old Faithful Geyser eruptions

Data on the eruptions of the Old Faithful Geyser in Yellowstone National Park, Wyoming, USA, have been collected for about 150 years. The geyser was named “Old Faithful” due to the relatively predictable timing and length of its eruptions. The oldfaithful data set contains data on all 2097 eruptions recorded between 14 January 2017 and 29 December 2023.

oldfaithful
# A tibble: 2,097 × 4
   time                recorded_duration duration waiting
   <dttm>              <chr>                <dbl>   <dbl>
 1 2017-01-14 00:06:00 3m 16s                 196    5940
 2 2017-01-26 14:27:00 ~4m                    240    5820
 3 2017-01-27 23:57:00 2m 1s                  121    3900
 4 2017-01-30 15:09:00 ~4m                    240    5280
 5 2017-01-31 13:27:00 ~3.5m                  210    5580
 6 2017-01-31 15:00:00 ~4m                    240    5760
 7 2017-02-03 23:13:00 3m 25s                 205    5160
 8 2017-02-04 22:14:00 3m 34s                 214    5400
 9 2017-02-05 17:19:00 4m 0s                  240    6060
10 2017-02-05 19:00:00 4m 2s                  242    6060
# ℹ 2,087 more rows

The time stamp indicates the start time of each eruption, while recorded_duration gives what was transcribed by the observer. This has been converted to seconds to give the duration variable. The waiting variable is the time to the next eruption, again in seconds. Recordings are incomplete, especially during the winter months when observers may not be present.

Air quality in Beijing

The air_quality data set contains hourly data on air quality from 12 monitoring stations in Beijing, China, collected between 1 March 2013 and 28 February 2017. The data set contains 420,768 hourly observations of the concentration of various pollutants, including PM2.5 (particulate matter with diameter less than 2.5 microns), PM10 (particulate matter with diameter less than 10 microns), SO2 (sulphur dioxide), NO2 (nitrogen dioxide), CO (carbon monoxide), and O3 (ozone). The data set also includes several weather variables, including temperature, pressure, dew point, rainfall, wind direction and speed. Because it is a rather large data set, it does not come pre-loaded with the weird package, but can be obtained using the fetch_air_quality() function.

air_quality <- fetch_air_quality()
air_quality
# A tibble: 420,768 × 17
   station       year month   day  hour pm2_5  pm10   so2   no2    co    o3 temperature
   <chr>        <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>       <dbl>
 1 Aotizhongxin  2013     3     1     0     4     4     4     7   300    77        -0.7
 2 Aotizhongxin  2013     3     1     1     8     8     4     7   300    77        -1.1
 3 Aotizhongxin  2013     3     1     2     7     7     5    10   300    73        -1.1
 4 Aotizhongxin  2013     3     1     3     6     6    11    11   300    72        -1.4
 5 Aotizhongxin  2013     3     1     4     3     3    12    12   300    72        -2  
 6 Aotizhongxin  2013     3     1     5     5     5    18    18   400    66        -2.2
 7 Aotizhongxin  2013     3     1     6     3     3    18    32   500    50        -2.6
 8 Aotizhongxin  2013     3     1     7     3     6    19    41   500    43        -1.6
 9 Aotizhongxin  2013     3     1     8     3     6    16    43   500    45         0.1
10 Aotizhongxin  2013     3     1     9     3     8    12    28   400    59         1.2
# ℹ 420,758 more rows
# ℹ 5 more variables: pressure <dbl>, dew_point <dbl>, rainfall <dbl>,
#   wind_direction <chr>, wind_speed <dbl>

Wine prices and quality

The wine_reviews data set contains data on 111,592 wines from 42 countries, taken from the Wine Enthusiast Magazine during the week of 15 June 2017. The data set contains information on the winery and its location, the variety of grape used to make the wine, the year of harvest, the price of the wine in $US, and a points value that provides a measure of the quality of the wine based on a taster’s assessment on a scale of 0 to 100. Again, it does not come pre-loaded with the package, but can be obtained using the fetch_wine_reviews() function.

wine_reviews <- fetch_wine_reviews()
wine_reviews
# A tibble: 111,592 × 9
   country  state             region       winery variety  year points price description
   <chr>    <chr>             <chr>        <chr>  <chr>   <dbl>  <dbl> <dbl> <chr>      
 1 Portugal Douro             <NA>         Quint… Portug…  2011     87    15 This is ri…
 2 US       Oregon            Willamette … Rains… Pinot …  2013     87    14 Tart and s…
 3 US       Michigan          Lake Michig… St. J… Riesli…  2013     87    13 Pineapple …
 4 US       Oregon            Willamette … Sweet… Pinot …  2012     87    65 Much like …
 5 Spain    Northern Spain    Navarra      Tandem Tempra…  2011     87    15 Blackberry…
 6 Italy    Sicily & Sardinia Vittoria     Terre… Frappa…  2013     87    16 Here's a b…
 7 France   Alsace            Alsace       Trimb… Gewürz…  2012     87    24 This dry a…
 8 Germany  Rheinhessen       <NA>         Heinz… Gewürz…  2013     87    12 Savory dri…
 9 France   Alsace            Alsace       Jean-… Pinot …  2012     87    27 This has g…
10 US       California        Napa         Kirkl… Cabern…  2011     87    19 Soft, supp…
# ℹ 111,582 more rows

Synthetic standard Normal data

The n01 data set contains synthetic data on 10 variables, each generated independently from a Normal distribution with mean zero and variance one. So by definition, this data set contains no anomalies. Anomalies are added to these data in later chapters when testing algorithms, in order to check that the algorithms can identify the artificial anomalies.

n01
# A tibble: 1,000 × 10
       v1      v2      v3      v4     v5     v6      v7     v8     v9     v10
    <dbl>   <dbl>   <dbl>   <dbl>  <dbl>  <dbl>   <dbl>  <dbl>  <dbl>   <dbl>
 1 -0.626  1.13   -0.886   0.739  -1.13  -1.52  -0.619  -1.33   0.264 -1.22  
 2  0.184  1.11   -1.92    0.387   0.765  0.629 -1.11    0.952 -0.829 -0.946 
 3 -0.836 -0.871   1.62    1.30    0.571 -1.68  -2.17    0.860 -1.46   0.0914
 4  1.60   0.211   0.519  -0.804  -1.35   1.18  -0.0313  1.06   1.68   0.701 
 5  0.330  0.0694 -0.0558 -1.60   -2.03   1.12  -0.260  -0.351 -1.54   0.673 
 6 -0.820 -1.66    0.696   0.933   0.590 -1.24   0.534  -0.131 -0.191  1.27  
 7  0.487  0.811   0.0535  1.81   -1.41  -1.23  -0.559   0.764  1.02  -1.45  
 8  0.738 -1.91   -1.31   -0.0565  1.61   0.598  1.61   -0.494  0.547  1.42  
 9  0.576 -1.25   -2.12    1.89    1.84   0.299  0.557   1.11   0.755 -1.59  
10 -0.305  0.998  -0.208   1.58    1.37  -0.110  0.186   1.46  -0.420  0.246 
# ℹ 990 more rows

1.5 Strip plots and scatterplots

When there are no more than a few thousand observations, and only one or two variables, it is useful to start with simple plots that allow us to look at the observations directly with no processing or modelling that may hide what is going on.

Let’s start with some examples using only one or two variables. These examples will be revisited in later chapters as new anomaly detection tools and graphics are introduced.

Example: Don Bradman’s batting averages

Don Bradman was an Australian cricketer in the first half of the 20th century, and is renowned as the best batter to ever play the game. The most common measure of a batter’s ability is their career average — the total number of runs made divided by the number of times they were dismissed. Figure 1.2 shows a strip plot of the career averages for all 1254 men and women who have played Test cricket and batted at least 20 times.

Code
cricket_batting |>
  filter(Innings >= 20) |>
  ggplot(aes(x = Average, y = 1)) +
  geom_jitter(width = 0, alpha = 0.5) +
  scale_y_discrete() +
  labs(y = "", x = "Career batting average")
Figure 1.2: Career batting averages for all men and women to have played Test cricket and batted at least 20 times. The anomaly is Don Bradman, who averaged 99.94 over his career.

The points are “jittered” vertically to reduce overplotting, and made slightly transparent to show where overplotting occurs. There is an obvious anomaly on the right of the plot; this point is Don Bradman, who averaged 99.94 over his career. Clearly, Don Bradman was much better than any of the other men and women who have played Test cricket.

Example: Old Faithful eruption durations

Next consider the duration of eruptions of the Old Faithful Geyser, shown in Figure 1.3.

Code
oldfaithful |>
  ggplot(aes(x = duration, y = 1)) +
  geom_jitter(width = 0, alpha = 0.5) +
  labs(y = "", x = "Duration (seconds)") +
  scale_y_discrete()
Figure 1.3: Old Faithful eruption durations between 2017 and 2023.

We see that almost all the eruptions were between 100 and 300 seconds in length, with one extremely short duration of 1 second, and two other unusually short eruption durations. If we view the recorded durations, we can see a problem:

oldfaithful |> arrange(duration)
# A tibble: 2,097 × 4
   time                recorded_duration       duration waiting
   <dttm>              <chr>                      <dbl>   <dbl>
 1 2018-04-25 19:08:00 1s                             1    5700
 2 2022-12-07 17:19:00 ~4 30s                        30    5220
 3 2023-07-04 12:03:00 ~1 minute 55ish seconds       60    4920
 4 2022-11-17 22:53:00 1m 28s                        88    3540
 5 2022-11-20 22:43:00 1m 29s                        89    3480
 6 2020-06-18 02:00:00 1min 32 sec                   92    3600
 7 2021-08-14 21:38:06 1m32s                         92    3882
 8 2022-10-02 19:39:00 1m 32s                        92    3900
 9 2020-09-25 20:00:00 1m33s                         93    3540
10 2023-10-12 20:08:00 1m33s                         93    4080
# ℹ 2,087 more rows

While the first duration of 1 second appears to be what was recorded (but is surely a recording error), the next two short durations (of 30 and 60 seconds) are simply due to errors in converting the recorded duration to a numerical value. So we can be confident that these three short durations are genuine anomalies.

However, Figure 1.3 reveals another feature of the data. The majority of observations are between 200 and 300 seconds, with a smaller group at around 120 seconds. Few observations fall between 140 and 180 seconds. Those that do might be considered “inliers” — anomalous points that lie within the range of the rest of the data but in regions of low density.

The two clusters of observations characterise two eruption modes for the Old Faithful Geyser: short durations (around 2 minutes in length) and long durations (between 3 and 5 minutes in length). There was an earthquake in 1998 that changed the distribution of durations. Before 1998, the durations were more evenly split between the two clusters, but currently the long durations are much more common.

The oldfaithful data set also contains the time between eruptions. For each row, waiting gives the time to the following eruption. The relationship between duration and waiting is used to predict when the next eruption will happen, based on the duration of the most recent eruption.

Code
oldfaithful |>
  ggplot(aes(x = duration, y = waiting)) +
  geom_point(alpha = 0.5) +
  labs(y = "Waiting time to next eruption (seconds)", x = "Duration (seconds)")
Figure 1.4: Old Faithful eruption durations and waiting times between 2017 and 2023.

Figure 1.4 shows the duration of each eruption and the waiting time to the next eruption. It reveals some anomalies that occur due to the combination of the two variables, although they do not appear anomalous within the data on any one of the variables. For example, there are two eruptions of 110–120 seconds, followed by waiting times of over 6000 seconds. Neither the waiting time nor the duration is unusual on its own, but the combination is anomalous. Similarly, there is one eruption of about 240 seconds, followed by a waiting time of about 3000 seconds. The waiting time is the second-smallest overall, but appears even more extraordinary given the long duration of the previous eruption. Every other eruption of similar duration was followed by a waiting time of at least 4500 seconds, and typically almost twice as long.

Example: Wine prices and quality

Figure 1.5 shows a scatterplot of data on 4,553 Syrah wines (also known as Shiraz). The review points provide a measure of the quality of the wine (at least according to one taster’s palate). As expected, the price of the wine increases with the quality, although there is considerable variation, and some very expensive wines are rated of relatively low quality, while there are a few exceptional wines at bargain prices.

Code
wine_reviews |>
  filter(variety %in% c("Shiraz", "Syrah")) |>
  select(points, price) |>
  ggplot(aes(y = price, x = points)) +
  geom_jitter(height = 0, width = 0.3, alpha = 0.5) +
  scale_y_log10()
Figure 1.5: Wine prices and review points for Shiraz/Syrah wines.

The jittering in the horizontal direction helps reduce overplotting as points is always an integer value. This adds a small amount of random noise to the points variable, but not so much that it overlaps with the neighbouring values. The price is shown on a log scale to allow all the points to be seen more clearly.

Here the most interesting observations are the ones that have an unusual price given their points value. For example, the lowest-priced wine above 95 points is a 2007 Syrah from the Rulo winery in the Columbia Valley, Washington. It is an anomaly given its high points value and low price, although neither the price nor the points value is particularly unusual. There are also two very expensive wines that do not have a rating to match, with points values in the low 90s. These can also be considered anomalies.

wine_reviews |>
  filter(
    variety %in% c("Shiraz", "Syrah"),
    points > 95
  ) |>
  filter(price == min(price)) |>
  select(country, state, region, winery, variety, year, points, price)
# A tibble: 1 × 8
  country state      region          winery variety  year points price
  <chr>   <chr>      <chr>           <chr>  <chr>   <dbl>  <dbl> <dbl>
1 US      Washington Columbia Valley Rulo   Syrah    2007     96    20

A similar phenomenon occurs whenever you consider additional variables. An anomaly in three dimensions may not appear anomalous in any pair of variables. As the number of dimensions increases, there are more ways for observations to be anomalous, but it is increasingly difficult to find them.

While strip plots and scatterplots are useful for finding anomalies in small- to moderate-sized data sets with one or two numerical variables, we will need alternative tools once we have three or more variables, or a large data set, or non-numerical data.

Chapter 9 considers the problem of high dimensions, while various types of non-numerical data are considered in the later chapters of the book.

Example: Synthetic standard Normal data

When we have many variables, showing the pairwise scatterplots in a matrix is a useful way to see a lot of information quickly. This is called a scatterplot matrix, and can be produced using the GGally package.

Figure 1.6 shows the scatterplot matrix of all 10 variables in the n01 data set. Some transparency has been used to help reduce the overplotting, but with 1000 observations in each small point cloud, it is hard to see any detail other than around the edges.

Code
n01 |>
  GGally::ggpairs(mapping = aes(alpha = 0.02))
Figure 1.6: Scatterplots of all pairs of the synthetic n01 data, where each variable has been generated from independent standard Normal distributions.

Any points that appear slightly outside the main clouds of points are not genuine anomalies, because they were generated from the same N(0,1) distribution as the rest of the data.