- Table of Contents
- 1 Tidy Data
- 2 Computing with R
- 3 Basic R Commands
- 4 Files and documents
- 5 Introduction to Data Graphics
- 6 Frames, glyphs, and other components of graphics
- 7 Data Wrangling
- 8 Graphics and Their Grammar
- 9 More Data Verbs
- 10 Joining two data frames
- 11 Wide versus Narrow Data
- 12 Ranks
- 13 Graphing Networks
- 14 Statistics
- 15 Data Scraping and Cleaning
- 16 Using Regular Expressions
- 17 Working with Many Variables
- Exercises
- Project: Popular names
- Project: Bicycle Sharing
- Project: Bird species
- Project: Statistics of Gene Expression
- Project: Scraping Nuclear Reactors
- Project: Joining the urban population
- Appendix: Setting up R
- 18 Appendix: R Programming Style Guide
- 19 Notes for typesetting book
- 20 Appendix: GitHub-RStudio Configuration

Up to now, the emphasis has been on individual cases. Data graphics, for instance, translate each case into a representation in terms of a glyph’s graphical attributes: position, color, size, shape, etc.

There are many occasions where a different emphasis is called for: representing the *collective properties***Collective properties**: Features of groups of cases. of cases. You’ve seen simple collective properties calculated with *summary functions*: mean, median, max, etc. The concern here is detailed collective descriptions, aspects of the collective that cannot be summed up in a single number.

Statistics is the area of science concerned with characterizing case-to-case variation and the collective properties of cases, while also quantifying our uncertainty. Statistics provides many important insights into the collection and interpretation of data. “Data science” is a collaboration between statistics and computer science. Although this book is mainly about computing, a solid grasp of statistics is an important foundation for effective work with data.

A central topic in statistics is the precision with which quantities can be calculated from data. This is not precision in the sense of the correctness of calculations, but has to do with the randomness that inevitably comes into play when selecting a sample of cases from a larger set of possibilities.

This chapter will touch on some important ideas from statistics, especially “confidence intervals” and “confidence band.” The techniques by which computers can learn from data, presented in Chapter 17, have embedded in them considerable statistical theory, although statistics itself is not the subject of that chapter.

The main emphasis of this chapter will be the statistical graphics used to display variation among cases, particularly the distribution of values of one variable or several of variables.

To start, consider the `weight`

variable in the `NCHS`

data. Of course, weight varies from person to person; there is a distribution of weights from case to case. Sometimes it’s helpful to show this distribution, what values are common, what values are rare, what values never show up.

Naïvely, this might be done by drawing a weight axis and putting on it a point for each case, as in Figure 14.1. This graph shows some familiar facts: humans tend not to be lighter than a few kilograms, and tend not to be heavier than about 150 kg. Between these limits, there seems to be no detail.

This is misleading, the result of having so many cases (29375) to plot. All those cases lead to ink saturation. One way to overcome this problem is by using transparency, another is to ** jitter** the individual points.

```
NCHS %>%
ggplot(aes(x = weight, y = 1)) +
geom_point(alpha = 0.02, position = "jitter" ) +
xlab("Weight (kg)") +
ylab("") + theme_bw() + scale_color_grey()
```

Jittering produces a much more satisfactory display; the ink saturation has been greatly reduced and there is more detail. For instance, the most common weights are between 55 and 90 kg, and that weights less than 20 kg are also pretty common. There aren’t so many people with weights near 30kg, and few over 120 kg.

The visual impression is due to collective properties of the data. Every individual glyph is identical, but for weights where the glyphs have a high ** density**,

The collective property of density is conventionally displayed as a another kind of glyph, as in Figure 14.3, that displays the collective density property using the height of a function instead of the shade of darkness.

```
NCHS %>%
ggplot(aes(x = weight) ) +
geom_density(color = "gray", fill = "gray", alpha = 0.75) +
xlab("Weight(kg)") + ylab("Density (1/kg)")
```

In this format, the *height* of the band indicates the density of cases. You can’t see individual cases, just the collective property of the density at each weight.

To help you see the translation between the density as vertical position and the density as darkness, Figure 14.4 overlays the two depictions of density in Figures 14.2 and 14.3.

```
NCHS %>%
ggplot(aes(x = weight)) +
geom_density(alpha = 0.75, color = "gray", fill = "gray") +
geom_point(alpha = 0.02, aes(y = 0.002),
position = position_jitter(height = 0.002)) +
xlab("Weight (kg)") +
ylab( "Density (1/kg)")
```

Graphs of the distribution of density can be used to compare different groups. You need merely indicate which variable should be used for grouping. For instance, Figure 14.5 displays the distribution density of body weight for each sex:

```
ggplot(NCHS, aes(x = weight, group = sex) ) +
geom_density(aes(color = sex, fill = sex), alpha = 0.5) +
xlab("Weight (kg)") +
ylab("Density (1/kg)") +
theme(legend.position = "top")
```

Graphs of density distributions often have a simple shape. This allows you to place the distributions side by side for comparison. For instance, suppose you arrange to divide people into age groups.

```
NCHS <-
NCHS %>%
mutate(ageGroup = mosaic::ntiles(age, n = 6, format = "interval"))
```

The age group can be used to define facets for a graphic, as in Figure 14.6.

```
NCHS %>%
ggplot( aes(x = weight, group = sex) ) +
geom_density(aes(color = sex, fill = sex), alpha = 0.75) +
facet_wrap( ~ ageGroup, nrow = 1 ) +
xlab("Weight (kg)") +
ylab( "Density (1/kg)") +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
```

Figure 14.6 tells a rich story. For young children the two sexes have almost identical distributions. For kids from 5 to 13 years, the distributions are still similar, though you can see that some girls have grown faster, producing a somewhat higher density near 50 kg. From the teenage years on, the distribution for men is shifted to somewhat higher weight than for women. This shift stays pretty much constant for the rest of life.

The detail in the density curves can be visually overwhelming: there’s a lot of detail in each density curve. To simplify the graph, sometimes a more stylized depiction of the distribution is helpful. This makes it feasible to put the distributions side-by-side for comparison. (Figure 14.7) The most common such depiction is the ** box-and-whisker** glyph.

The box-and-whisker glyph shows the extent of the middle 50% of the distribution as a box. The whiskers show the range of the top and bottom quarter of the distribution. When there are uncommon, extremely high or low values — e.g., “outliers” — they are displayed as individual dots for each of the outlier cases.

```
NCHS %>%
ggplot(aes(y = weight, x = ageGroup)) +
geom_boxplot(aes(color = ageGroup, fill = ageGroup),
alpha = 0.25, outlier.size = 2, outlier.colour = "gray") +
facet_wrap( ~ sex ) +
xlab("Age Group (yrs)") +
ylab("Weight (kg)") +
theme(legend.position = "top") +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
```

The *violin glyph***Violin glyph**: Shows distributions like a box and whisker glyph but smoother. provides a similar ease of comparison to the box-and-whisker glyph, but shows more detail in the density. (Figure 14.8)

```
NCHS %>%
ggplot(aes(y = weight, x = ageGroup)) +
geom_violin(fill = "gray") +
facet_wrap( ~ sex ) +
ylab("Weight (kg)") +
xlab( "Age Group (yrs)") +
theme(legend.position = "top") +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
```

Both the box-and-whisker and violin glyphs use ink efficiently. This allows you to show other data for comparison. For instance, Figure 14.9 compares the weight of people with and without diabetics, broken down by age and sex. You can see that diabetics tend to be heavier than non-diabetics, especially for ages 19+.

```
NCHS %>%
ggplot(aes(y = weight, x = ageGroup )) +
geom_boxplot(aes(fill = diabetic),
position = position_dodge(width = 0.8),
outlier.size = 1, outlier.colour = "gray", alpha = 0.75) +
facet_grid( sex ~ .) +
ylab("Weight (kg)") +
xlab( "Age Group (yrs)") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
```

Statistical inference refers to an assessment of the *precision* or *strength of evidence* for a claim. For instance, in interpreting the plot above, it was claimed that diabetics tend to be heavier than non-diabetics. Perhaps this is just an accident. Might it be that there are so few diabetics that their weight distribution is not well known?

The *confidence interval* of a statistic indicates the uncertainty of an estimate due to the size of the sample. Smaller-sized samples provide weaker evidence and their confidence intervals are broader than those produced by larger-sized samples.

A box-and-whiskers glyph can show the confidence interval of the median by means of a “notch”. (Figure 14.10) Overlap between the notches in two boxes indicates that the evidence for a difference is weak.

```
NCHS %>%
ggplot(aes(y = weight, x = ageGroup )) +
geom_boxplot(aes(fill = diabetic),
notch = TRUE,
position = position_dodge(width = 0.8),
outlier.size = 1, outlier.colour = "gray") +
facet_grid(sex ~ .) +
ylab("Weight (kg)") +
xlab( "Age Group (yrs)") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
```

A *function* is one way of describing a relationship between input and output. Often it’s helpful to use a function estimated from data.

For example, consider the relationship between weight and age in the NCHS data. Is it the same for diabetics and non-diabetics?

```
NCHS %>%
ggplot(aes(x = age, y = weight, color = diabetic)) +
stat_smooth(se = FALSE) +
geom_point(alpha = 0.02) +
ylim(0, 120) +
theme(legend.position = "top")
```

There are two functions in Figure 14.11, each calculated by `stat_smooth()`

from the age and weight variables. One function is for diabetics, the other for non-diabetics. Each function gives just one weight value for each age, rather than the distribution seen in the raw data. That value is more or less the mean weight at each age. From the functions, it seems that the diabetics are consistently heavier than the non-diabetics, at least on average. At age 30, that average difference is more than 20kg; it is less for people near 80.

On it’s face, Figure 14.11 suggests that, for any age, the mean weight of diabetics is higher than that of non-diabetics. Before drawing such a conclusion, however, it’s important to know how precisely the functions can be estimated from the data.

The calculation of the functions are exact, but the specific function produced depends on the particular set of cases in the data. Imagine that the original data frame consisted of cases that had been randomly selected from all possible cases. Suppose a new set of cases were collected, also randomly selected. The function calculated based on that new set would likely differ *somewhat* from the function calculated from the original data frame. The point of a statistical *confidence interval* is to provide a quantitative meaning to “somewhat.”

When applying the idea of confidence intervals to a function, one arrives at bands around the function: the ** confidence band**s.

The variation that stems from random sampling of cases is so important to interpreting the graphic that the default in `stat_smooth()`

is to calculate and show the confidence band unless the user specifically asks otherwise.

```
NCHS %>%
ggplot(aes(x = age, y = weight, color = diabetic )) +
stat_smooth( ) +
geom_point(alpha = 0.03) +
ylim(0, 120) +
theme(legend.position = "top")
```

Confidence intervals and bands are widely mis-interpreted. The confidence band does not show the range of cases, it shows the precision with which the statistic or model function is estimated. So it’s wrong to say something like ‘diabetics are heavier than non-diabetics’. Instead, the statement justified by the separation between the confidence bands is ‘the mean weight of diabetics (taking into account age) is greater than that of non-diabetics.’ Long winded? Yes. Maybe that’s why confidence intervals and bands are so widely mis-interpreted.

The function for non-diabetics has a narrow confidence band; you have to look hard to even see the gray zone. The confidence band for diabetics, however, is noticeably wide. For ages below about 20, the non-diabetic and diabetic confidence bands overlap. This means that there is only weak evidence that diabetics as a group in this age group differ in weight from non-diabetics. Around age 20, the two functions’ confidence bands do not overlap. This indicates stronger evidence that the groups in the 20+ age bracket do differ in **average** weight.

You might ask why the confidence band for the diabetics is so much wider than for the non-diabetics? And why is the diabetic confidence band broad in some places and narrow in others?

The width of a confidence band depends on three things:

- the amount of variation in the value of y at or near the x value.
- the number of cases close to the x value
- the extent to which the function is an extrapolation.

The functions in Figures 14.11 and 14.12 are called ** smoother**s.

A much more commonly used function — the “linear” function — is utterly stiff; it can’t bend at all. You can construct this sort of function from the data with

`method = lm`

as an argument to `stat_smooth()`

.```
NCHS %>%
ggplot(aes(x = age, y = weight,
color = diabetic, fill = diabetic )) +
stat_smooth(method = lm) +
geom_point(alpha = 0.02) +
ylim(0,120) +
theme(legend.position = "top")
```

In this situation, a linear function is too stiff. The function for non-diabetics slopes up at high ages not because older non-diabetics in fact weigh less than middle-aged diabetics, but because the line needs to accommodate both the children (light in weight) and the adults (who are heavier).

You’ll often see linear functions in the scientific literature. This is for several reasons, some good and some bad:

- Linear functions generally have tighter confidence bands than smoothers. (A good reason)
- People are familiar with straight-line functions from high school. (A bad reason)
- Many people don’t know about non-linear functions such as a smoother. (A bad reason)

A simple rule of thumb: When in doubt, use a smoother.