Chapter page 10 / 385 Exploring numerical data
English

5  Exploring numerical data

This chapter focuses on exploring numerical data using summary statistics and visualizations. The summaries and graphs presented in this chapter are created using statistical software; however, since this might be your first exposure to the concepts, we take our time in this chapter to detail how to create them. Mastery of the content presented in this chapter will be crucial for understanding the methods and techniques introduced in the rest of the book.

Consider the loan_amount variable from the loan50 dataset, which represents the loan size for each of 50 loans in the dataset.

This variable is numerical since we can sensibly discuss the numerical difference of the size of two loans. On the other hand, area codes and zip codes are not numerical, but rather they are categorical variables.

Throughout this chapter, we will apply numerical methods using the loan50 and county datasets, which were introduced in Section 1.2. If you’d like to review the variables from either dataset, see Tables Table 1.4 and Table 1.6.

The county data can be found in the usdata R package and the loan50 data can be found in the openintro R package.

5.1 Scatterplots for paired data

A scatterplot provides a case-by-case view of data for two numerical variables. In Figure 1.2, a scatterplot was used to examine the homeownership rate against the percentage of housing units that are in multi-unit structures (e.g., apartments) in the county dataset. Another scatterplot is shown in Figure 5.1, comparing the total income of a borrower total_income and the amount they borrowed loan_amount for the loan50 dataset. In any scatterplot, each point represents a single case. Since there are 50 cases in loan50, there are 50 points in Figure 5.1.

A scatterplot with total income on the x-axis and loan amount on the y-axis. The relationship is moderately positive.
Figure 5.1: A scatterplot of loan amount versus total income for the loan50 dataset.

Looking at Figure 5.1, we see that there are many borrowers with income below $100,000 on the left side of the graph, while there are a handful of borrowers with income above $250,000.

A scatterplot with poverty rate on the x-axis and median household income on the y-axis. The relationship is negative and curvilinear. The bulk of the points fall with a poverty rate of 10% to 20% and a median household income of $25K to $75K.
Figure 5.2: A scatterplot of the median household income against the poverty rate for the county dataset. Data are from 2017. A statistical model has also been fit to the data and is shown as a dashed line.

Figure 5.2 shows a plot of median household income against the poverty rate for 3142 counties in the US. What can be said about the relationship between these variables?


The relationship is evidently nonlinear, as highlighted by the dashed line. This is different from previous scatterplots we have seen, which indicate very little, if any, curvature in the trend.

What do scatterplots reveal about the data, and how are they useful?1

Describe two variables that would have a horseshoe-shaped association in a scatterplot \((\cap\) or \(\frown).\)2

5.2 Dot plots and the mean

Sometimes we are interested in the distribution of a single variable. In these cases, a dot plot provides the most basic of displays. A dot plot is a one-variable scatterplot; an example using the interest rate of 50 loans is shown in Figure 5.3.

A dot plot of interest rate (ranging from about 5% to 25%). The distribution is right skewed, and the mean is shown at an interest rate of about 11%.
Figure 5.3: A dot plot of interest rate for the loan50 dataset. The rates have been rounded to the nearest percent in this plot, and the distribution’s mean is shown as a red triangle.

The mean, often called the average is a common way to measure the center of a distribution of data. To compute the mean interest rate, we add up all the interest rates and divide by the number of observations.

The sample mean is often labeled \(\bar{x}.\) The letter \(x\) is being used as a generic placeholder for the variable of interest and the bar over the \(x\) communicates we are looking at the average interest rate, which for these 50 loans is 11.57%. It’s useful to think of the mean as the balancing point of the distribution, and it’s shown as a triangle in Figure 5.3.

Mean.

The sample mean can be calculated as the sum of the observed values divided by the number of observations:

\[ \bar{x} = \frac{x_1 + x_2 + \cdots + x_n}{n} \]

Examine the equation for the mean. What does \(x_1\) correspond to? And \(x_2\)? Can you infer a general meaning to what \(x_i\) might represent?3

What was \(n\) in this sample of loans?4

The loan50 dataset represents a sample from a larger population of loans made through Lending Club. We could compute a mean for the entire population in the same way as the sample mean. However, the population mean has a special label: \(\mu.\) The symbol \(\mu\) is the Greek letter mu and represents the average of all observations in the population. Sometimes a subscript, such as \(_x,\) is used to represent which variable the population mean refers to, e.g., \(\mu_x.\) Oftentimes it is too expensive to measure the population mean precisely, so we often estimate \(\mu\) using the sample mean, \(\bar{x}.\)

The Greek letter \(\mu\) is pronounced mu, listen to the pronunciation here.

Although we do not have an ability to calculate the average interest rate across all loans in the populations, we can estimate the population value using the sample data. Based on the sample of 50 loans, what would be a reasonable estimate of \(\mu_x,\) the mean interest rate for all loans in the full dataset?


The sample mean, 11.57, provides a rough estimate of \(\mu_x.\) While it is not perfect, this is our single best guess point estimate of the average interest rate of all the loans in the population under study. In Chapter 11 and beyond, we will develop tools to characterize the accuracy of point estimates, like the sample mean. As you might have guessed, point estimates based on larger samples tend to be more accurate than those based on smaller samples.

The mean is useful because it allows us to rescale or standardize a metric into something more easily interpretable and comparable. Suppose we would like to understand if a new drug is more effective at treating asthma attacks than the standard drug. A trial of 1,500 adults is set up, where 500 receive the new drug, and 1000 receive a standard drug in the control group. Results of this trial are summarized in Table 5.1.

Table 5.1: Results of a trial of 1500 adults that suffer from asthma.
New drug Standard drug
Number of patients 500 1000
Total asthma attacks 200 300

Comparing the raw counts of 200 to 300 asthma attacks would make it appear that the new drug is better, but this is an artifact of the imbalanced group sizes.

Instead, we should look at the average number of asthma attacks per patient in each group:

  • New drug: \(200 / 500 = 0.4\) asthma attacks per patient
  • Standard drug: \(300 / 1000 = 0.3\) asthma attacks per patient

The standard drug has a lower average number of asthma attacks per patient than the average in the treatment group.

Come up with another example where the mean is useful for making comparisons.


Emilio opened a food truck last year where he sells burritos, and his business has stabilized over the last 3 months. Over that 3-month period, he has made $11,000 while working 625 hours. Emilio’s average hourly earnings provides a useful statistic for evaluating whether his venture is, at least from a financial perspective, worth it:

\[ \frac{\$11000}{625\text{ hours}} = \$17.60\text{ per hour} \]

By knowing his average hourly wage, Emilio now has put his earnings into a standard unit that is easier to compare with many other jobs that he might consider.

Suppose we want to compute the average income per person in the US. To do so, we might first think to take the mean of the per capita incomes across the 3,142 counties in the county dataset. What would be a better approach?


The county dataset is special in that each county actually represents many individual people. If we were to simply average across the income variable, we would be treating counties with 5,000 and 5,000,000 residents equally in the calculations. Instead, we should compute the total income for each county, add up all the counties’ totals, and then divide by the number of people in all the counties. If we completed these steps with the county data, we would find that the per capita income for the US is $30,861. Had we computed the simple mean of per capita income across counties, the result would have been just $26,093!

This example used what is called a weighted mean. For more information on this topic, check out the following online supplement regarding weighted means.

5.3 Histograms and shape

Dot plots show the exact value for each observation. They are useful for small datasets but can become hard to read with larger samples. Rather than showing the value of each observation, we prefer to think of the value as belonging to a bin. For example, in the loan50 dataset, we created a table of counts for the number of loans with interest rates between 5.0% and 7.5%, then the number of loans with rates between 7.5% and 10.0%, and so on. Observations that fall on the boundary of a bin (e.g., 10.00%) are allocated to the lower bin. The tabulation is shown in Table 5.2, and the binned counts are plotted as bars in Figure 5.4 into what is called a histogram. Note that the histogram resembles a more heavily binned version of the stacked dot plot shown in Figure 5.3.

Table 5.2: Counts for the binned interest rate data.
Interest rate Count
(5% - 7.5%] 11
(7.5% - 10%] 15
(10% - 12.5%] 8
(12.5% - 15%] 4
(15% - 17.5%] 5
(17.5% - 20%] 4
(20% - 22.5%] 1
(22.5% - 25%] 1
(25% - 27.5%] 1
A histogram of interest rate (ranging from about 5% to 25%). The distribution is right skewed.
Figure 5.4: A histogram of interest rate. This distribution is strongly skewed to the right.

Histograms provide a view of the data density. Higher bars represent where the data are relatively more common. For instance, there are many more loans with rates between 5% and 10% than loans with rates between 20% and 25% in the dataset. The bars make it easy to see how the density of the data changes relative to the interest rate.

Histograms are especially convenient for understanding the shape of the data distribution. Figure 5.4 suggests that most loans have rates under 15%, while only a handful of loans have rates above 20%. When the distribution of a variable trails off to the right in this way and has a longer right tail, the shape is said to be right skewed.5

A density plot of interest rate (ranging from about 5% to 25%). The distribution is right skewed.
Figure 5.5: A density plot of interest rate. Again, the distribution is strongly skewed to the right.

Figure 5.5 shows a density plot which is a smoothed out histogram. The technical details for how to draw density plots (precisely how to smooth out the histogram) are beyond the scope of this text, but you will note that the shape, scale, and spread of the observations are displayed similarly in a histogram as in a density plot.

Variables with the reverse characteristic – a long, thinner tail to the left – are said to be left skewed. We also say that such a distribution has a long left tail. Variables that show roughly equal trailing off in both directions are called symmetric.

When data trail off in one direction, the distribution has a long tail. If a distribution has a long left tail, it is left skewed. If a distribution has a long right tail, it is right skewed.

Besides the mean (since it was labeled), what can you see in the dot plot in Figure 5.3 that you cannot see in the histogram in Figure 5.4?6

In addition to looking at whether a distribution is skewed or symmetric, histograms can be used to identify modes. A mode is represented by a prominent peak in the distribution. There is only one prominent peak in the histogram of interest_rate.

A definition of mode sometimes taught in math classes is the value with the most occurrences in the dataset. However, for many real-world datasets, it is common to have no observations with the same value in a dataset, making this definition impractical in data analysis.

Figure 5.6 shows histograms that have one, two, or three prominent peaks. Such distributions are called unimodal, bimodal, and multimodal, respectively. Any distribution with more than two prominent peaks is called multimodal. Notice that there was one prominent peak in the unimodal distribution with a second less prominent peak that was not counted since it only differs from its neighboring bins by a few observations.

Three separate histograms on fabricated data. The first histogram shows a unimodal distribution, the second histogram shows a bimodal distribution, and the third histogram shows a multimodal distribution.
Figure 5.6: Counting only prominent peaks, the distributions are (left to right) unimodal, bimodal, and multimodal. Note that the left plot is unimodal because we are counting prominent peaks, not just any peak.

Figure 5.4 reveals only one prominent mode in the interest rate. Is the distribution unimodal, bimodal, or multimodal?


Remember that uni stands for 1 (think unicycles), and bi stands for 2 (think bicycles).

Height measurements of young students and adult teachers at an elementary school were taken. How many modes would you expect in this height dataset?7

Looking for modes isn’t about finding a clear and correct answer about the number of modes in a distribution, which is why prominent is not rigorously defined in this book. The most important part of this examination is to better understand your data.

5.4 Variance and standard deviation

The mean was introduced as a method to describe the center of a variable, and variability in the data is also important. Here, we introduce two measures of variability: the variance and the standard deviation. Both of these are very useful in data analysis, even though their formulas are a bit tedious to calculate by hand. The standard deviation is the easier of the two to comprehend, as it roughly describes how far away the typical observation is from the mean.

We call the distance of an observation from its mean its deviation. Below are the deviations for the \(1^{st},\) \(2^{nd},\) \(3^{rd},\) and \(50^{th}\) observations in the interest_rate variable:

\[ \begin{aligned} x_1 - \bar{x} &= 10.9 - 11.57 = -0.67 \\ x_2 - \bar{x} &= 9.92 - 11.57 = -1.65 \\ x_3 - \bar{x} &= 26.3 - 11.57 = 14.73 \\ &\vdots \\ x_{50} - \bar{x} &= 6.08 - 11.57 = -5.49 \\ \end{aligned} \]

If we square these deviations and then take an average, the result is equal to the sample variance, denoted by \(s^2\):

\[ s^2 = \frac{(-0.67)^2 + (-1.65)^2 + (14.73)^2 + \cdots + (-5.49)^2}{50 - 1} = \frac{0.45 + 2.72 + \cdots + 30.14}{49} = 25.52 \]

We divide by \(n - 1,\) rather than dividing by \(n,\) when computing a sample’s variance. There’s some mathematical nuance here, but the end result is that doing this makes this statistic slightly more reliable and useful.

Notice that squaring the deviations does two things. First, it makes large values relatively much larger. Second, it gets rid of any negative signs.

Standard deviation.

The sample standard deviation can be calculated as the square root of the sum of the squared distance of each value from the mean divided by the number of observations minus one:

\[s = \sqrt{\frac{\sum_{i=1}^n (x_i - \bar{x})^2}{n-1}}\]

The standard deviation is defined as the square root of the variance:

\[s = \sqrt{25.52} = 5.05\]

While often omitted, a subscript of \(_x\) may be added to the variance and standard deviation, i.e., \(s_x^2\) and \(s_x^{},\) if it is useful as a reminder that these are the variance and standard deviation of the observations represented by \(x_1,\) \(x_2,\) …, \(x_n.\)

Variance and standard deviation.

The variance is the average squared distance from the mean. The standard deviation is the square root of the variance. The standard deviation is useful when considering how far the data are distributed from the mean.

The standard deviation represents the typical deviation of observations from the mean. Often about 68% of the data will be within one standard deviation of the mean and about 95% will be within two standard deviations. However, these percentages are not strict rules.

Like the mean, the population values for variance and standard deviation have special symbols: \(\sigma^2\) for the variance and \(\sigma\) for the standard deviation.

The Greek letter \(\sigma\) is pronounced sigma, listen to the pronunciation here.

A good description of the shape of a distribution should include modality and whether the distribution is symmetric or skewed to one side. Using Figure 5.7 as an example, explain why such a description is important.8

A histogram of the right-skewed variable, interest rates. Grey shading indicates the empirical rule cutoffs of one and two standard deviations. Because the variable is right-skewed, the empirical rule ranges do not capture the desired amoung of data, 68% and 95% respectively.

For the interest rate variable, 34 of the 50 loans (68%) had interest rates within 1 standard deviation of the mean, and 48 of the 50 loans (96%) had rates within 2 standard deviations. Usually about 68% of the data are within 1 standard deviation of the mean and 95% within 2 standard deviations, though this is far from a hard rule.
Three histograms of fabricated data with empirical rule shading of one and two standard deviations superimposed. The bimodal and right skewed histogram demonstrate that the empirical rule is not a good approximation. The empirical rule fits well to the unimodal bell-shaped distribution.
Figure 5.7: Three different population distributions with the same mean (0) and standard deviation (1).

Describe the distribution of the interest_rate variable using the histogram in Figure 5.4. The description should incorporate the center, variability, and shape of the distribution, and it should also be placed in context. Also note any especially unusual cases.


The distribution of interest rates is unimodal and skewed to the high end. Many of the rates fall near the mean at 11.57%, and most fall within one standard deviation (5.05%) of the mean. There are a few exceptionally large interest rates in the sample that are above 20%.

In practice, the variance and standard deviation are sometimes used as a means to an end, where the “end” is being able to accurately estimate the uncertainty associated with a sample statistic. For example, in Chapter 13 the standard deviation is used in calculations that help us understand how much a sample mean varies from one sample to the next.

5.5 Box plots, quartiles, and the median

A box plot summarizes a dataset using five statistics while also identifying unusual observations. Figure 5.8 provides a dot plot and a box plot of the interest_rate variable from the loan50 dataset.9

Two plots showing the same variable, interests rates. The top image is a dot plot, the bottom image is a box plot. Both images re-establish that the distribution of interest rates are right skewed.
(a) Dot plot
Two plots showing the same variable, interests rates. The top image is a dot plot, the bottom image is a box plot. Both images re-establish that the distribution of interest rates are right skewed.
(b) Box plot
Figure 5.8: Distribution of interest rates from the loan50 dataset.

The dark line inside the box represents the median, which splits the data in half. 50% of the data fall below this value and 50% fall above it. Since in the loan50 dataset there are 50 observations (an even number), the median is defined as the average of the two observations closest to the \(50^{th}\) percentile. Table 5.3 shows all interest rates, arranged in ascending order. We can see that the \(25^{th}\) and the \(26^{th}\) values are both 9.93, which corresponds to the thick line in Figure 5.8 (b).

Table 5.3: Interest rates from the loan50 dataset, arranged in ascending order.
1 2 3 4 5 6 7 8 9 10
1 5.31 5.31 5.32 6.08 6.08 6.08 6.71 6.71 7.34 7.35
10 7.35 7.96 7.96 7.96 7.97 9.43 9.43 9.44 9.44 9.44
20 9.92 9.92 9.92 9.92 9.93 9.93 10.42 10.42 10.90 10.90
30 10.91 10.91 10.91 11.98 12.62 12.62 12.62 14.08 15.04 16.02
40 17.09 17.09 17.09 18.06 18.45 19.42 20.00 21.45 24.85 26.30

When there are an odd number of observations, there will be exactly one observation that splits the data into two halves, and in such a case that observation is the median (no average needed).

Median: the number in the middle.

If the data are ordered from smallest to largest, the median is the observation right in the middle. If there are an even number of observations, there will be two values in the middle, and the median is taken as their average.

The second step in building a box plot is drawing a rectangle to represent the middle 50% of the data. The length of the box is called the interquartile range, or IQR for short. It, like the standard deviation, is a measure of variability in data. The more variable the data, the larger the standard deviation and IQR tend to be. The two boundaries of the box are called the first quartile (the \(25^{th}\) percentile, i.e., 25% of the data fall below this value) and the third quartile (the \(75^{th}\) percentile, i.e., 75% of the data fall below this value), and these are often labeled \(Q_1\) and \(Q_3,\) respectively.

Interquartile range (IQR).

The IQR interquartile range is the length of the box in a box plot. It is computed as \(IQR = Q_3 - Q_1,\) where \(Q_1\) and \(Q_3\) are the \(25^{th}\) and \(75^{th}\) percentiles, respectively.

A \(\alpha\) percentile is a number with \(\alpha\)% of the observations below and \(100-\alpha\)% of the observations above. For example, the \(90^{th}\) percentile of SAT scores is the value of the SAT score with 90% of students below that value and 10% of students above that value.

What percent of the data fall between \(Q_1\) and the median? What percent is between the median and \(Q_3\)?10

Extending out from the box, the whiskers attempt to capture the data outside of the box. The whiskers of a box plot reach to the minimum and the maximum values in the data, unless there are points that are considered unusually high or unusually low, which are identified as potential outliers by the box plot. These are labeled with a dot on the box plot. The purpose of labeling the outlying points – instead of extending the whiskers to the minimum and maximum observed values – is to help identify any observations that appear to be unusually distant from the rest of the data. There are a variety of formulas for determining whether a particular data point is considered an outlier, and different statistical software use different formulas. A commonly used formula is that any observation beyond \(1.5\times IQR\) away from the first or the third quartile is considered an outlier. In a sense, the box is like the body of the box plot and the whiskers are like its arms trying to reach the rest of the data, up to the outliers.

Outliers are extreme.

An outlier is an observation that appears extreme relative to the rest of the data. Examining data for outliers serves many useful purposes, including

  • identifying strong skew in the distribution,
  • identifying possible data collection or data entry errors, and
  • providing insight into interesting properties of the data.

Keep in mind, however, that some datasets have a naturally long skew and outlying points do not represent any sort of problem in the dataset.

Using the box plot in Figure 5.8 (b), estimate the values of the \(Q_1,\) \(Q_3,\) and IQR for interest_rate in the loan50 dataset.11

5.6 Robust statistics

How are the sample statistics of the interest_rate dataset affected by the observation, 26.3%? What would have happened if this loan had instead been only 15%? What would happen to these summary statistics if the observation at 26.3% had been even larger, say 35%? The three conjectured scenarios are plotted alongside the original data in Figure 5.9, and sample statistics are computed under each scenario in Table 5.4.

Table 5.4: A comparison of how the median, IQR, mean, and standard deviation change as the value of an extreme observation from the original interest data changes.
Robust
Not robust
Scenario Median IQR Mean SD
Original data 9.93 5.75 11.6 5.05
Move 26.3% to 15% 9.93 5.75 11.3 4.61
Move 26.3% to 35% 9.93 5.75 11.7 5.68
Three dot plots are displayed where a single point is highlighted. In the top plot is the original data where the highlighted point is the largest value, at 26.3%. The second plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 15%. The third plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 35%. The corresponding change in statistics are given in @tbl--robustOrNotTable.
(a) Original data
Three dot plots are displayed where a single point is highlighted. In the top plot is the original data where the highlighted point is the largest value, at 26.3%. The second plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 15%. The third plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 35%. The corresponding change in statistics are given in @tbl--robustOrNotTable.
(b) Move 26.3% to 15%
Three dot plots are displayed where a single point is highlighted. In the top plot is the original data where the highlighted point is the largest value, at 26.3%. The second plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 15%. The third plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 35%. The corresponding change in statistics are given in @tbl--robustOrNotTable.
(c) Move 26.3% to 35%
Figure 5.9: Dot plots of the original interest rate data and two modified datasets.

Which is more affected by extreme observations, the mean or median? Is the standard deviation or IQR more affected by extreme observations?12

The median and IQR are called robust statistics because extreme observations have little effect on their values: moving the most extreme value generally has little influence on these statistics. On the other hand, the mean and standard deviation are more heavily influenced by changes in extreme observations, which can be important in some situations.

The median and IQR did not change under the three scenarios in Table 5.4. Why might this be the case?


The median and IQR are only sensitive to numbers near \(Q_1,\) the median, and \(Q_3.\) Since values in these regions are stable in the three datasets, the median and IQR estimates are also stable.

You might not be surprised that the answer to the question “which is better, the mean or the median?” is: it depends. The two statistics measure different things, and so their use is dependent on the context in the analysis. Consider the following scenarios:

  • Is it better to measure the average profit per customer or the median profit per customer?
    • If concern is about the overall profit margin of the company, the mean is a better measure to assess what is happening across the company. The company could have a positive median profit per customer and still be unprofitable.
    • If concern is around understanding the profit per typical customer, possibly to understand the growth headroom for the company’s profit, the median profit per customer would tell you more about individual customer profits.
  • If you operate an app and want to know how long it takes for the app to open on your customers’ phones, do you want the mean amount of time or the median amount of time?
    • The mean leads to an understanding of the overall amount of time being wasted in opening the app.
    • The median tells you about the typical user experience.
    • However, if the app takes less than 5 milliseconds to launch for 50% of the users but more than 10 seconds to launch for 10% of the users, the median doesn’t give the information you need. In that scenario, you might want an upper percentile, like the 95th percentile.

The distribution of loan amounts in the loan50 dataset is right skewed, with a few large loans lingering out into the right tail. If you were wanting to understand the typical loan size, should you be more interested in the mean or median?13

Regardless of the choice of centrality statistic (either mean or median), for most analyses, it is important to consider more than just the centrality. Other statistics like upper and lower percentiles, IQR, or standard deviation provide information about the variability of the observations. And visualizing the data through a graphical representation will typically provide a wealth of information necessary for understanding the full data picture associated with the research question.

5.7 Transforming data

When data are very strongly skewed, we sometimes transform them, so they are easier to model. Figure 5.10 (a) and Figure 5.10 (b) show right-skewed distributions: distribution of the percentage of unemployed people and the distribution of the population in all counties in the United States. The distribution of population is more strongly skewed than the distribution of percentage unemployed, hence the log transformation results in a much bigger change in the shape of the distribution.

Consider the histogram of county populations shown in Figure 5.10 (c), which shows extreme skew. What characteristics of the plot keep it from being useful?


Nearly all of the data fall into the left-most bin, and the extreme skew obscures many of the potentially interesting details at the low values.

Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(a) Percentage unemployed
Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(b) log\(_{10}\)-transformed percentage unemployed
Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(c) Population
Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(d) log\(_{10}\)-transformed populations
Figure 5.10: Histograms of percentage unenmployed, population, and their log transformed versions in all US counties. For the plots of transformed variables, the x-value corresponds to the power of 10, e.g., 1 on the x-axis corresponds to \(10^1 =\) 10 and 5 on the x-axis corresponds to \(10^5=\) 100,000. Data are from 2017.

There are some standard transformations that may be useful for strongly right skewed data where much of the data is positive but clustered near zero. A transformation is a rescaling of the data using a function. For instance, a plot of the logarithm (base 10) of unemployment rates and county populations results in the new histograms in Figure 5.10 (b). The transformed data are symmetric, and any potential outliers appear much less extreme than in the original dataset. By reigning in the outliers and extreme skew, transformations often make it easier to build statistical models for the data.

Transformations can also be applied to one or both variables in a scatterplot. A scatterplot of the population change from 2010 to 2017 against the population in 2010 is shown in Figure 5.11 (a). It’s difficult to decipher any interesting patterns because the population variable is so strongly skewed. However, if we apply a log\(_{10}\) transformation to the population variable, as shown in Figure 5.11 (b), a positive association between the variables is revealed. In fact, we may be interested in fitting a trend line to the data when we explore methods around fitting regression lines in Chapter 7.

A pair of scatterplots is given. In both plots the y-axis is population change. In the first plot, the x-axis is given by the raw variable population before change, and most of the points are quite small, obscuring any  x-y relationship. In the second plot, the x-axis is given by the transformed variable log-10 of the population before change. The relationship between log-10 population before change and population change is seen to be moderately strong, positive, and linear.
(a) Population change
A pair of scatterplots is given. In both plots the y-axis is population change. In the first plot, the x-axis is given by the raw variable population before change, and most of the points are quite small, obscuring any  x-y relationship. In the second plot, the x-axis is given by the transformed variable log-10 of the population before change. The relationship between log-10 population before change and population change is seen to be moderately strong, positive, and linear.
(b) log\(_{10}\)-transformed population change
Figure 5.11: Scatterplots of population change and log\(_{10}\)-transformed population change vs. population before change.

Transformations other than the logarithm can be useful, too. For instance, the square root \((\sqrt{\text{original observation}})\) and inverse \(\bigg ( \frac{1}{\text{original observation}} \bigg )\) are commonly used by data scientists. Common goals in transforming data are to see the data structure differently, reduce skew, assist in modeling, or straighten a nonlinear relationship in a scatterplot.

5.8 Mapping data

The county dataset offers many numerical variables that we could plot using dot plots, scatterplots, or box plots, but they can miss the true nature of the data as geographic. When we encounter geographic data, we should create an intensity map, where colors are used to show higher and lower values of a variable. Figure 5.12 shows intensity maps for poverty rate in percent (poverty), unemployment rate in percent (unemployment_rate), homeownership rate in percent (homeownership), and median household income in $1000s (median_hh_income). The color key indicates which colors correspond to which values. The intensity maps are not generally very helpful for getting precise values in any given county, but they are very helpful for seeing geographic trends and generating interesting research questions or hypotheses.

What interesting features are evident in the poverty and unemployment rate intensity maps in Figure 5.12 (a) and Figure 5.12 (b)?


Poverty rates are evidently higher in a few locations. Notably, the deep south shows higher poverty rates, as does much of Arizona and New Mexico. High poverty rates are evident in the Mississippi flood plains a little north of New Orleans and in a large section of Kentucky.

The unemployment rate follows similar trends, and we can see correspondence between the two variables. In fact, it makes sense for higher rates of unemployment to be closely related to poverty rates. One observation that stands out when comparing the two maps: the poverty rate is much higher than the unemployment rate, meaning while many people may be working, they are not making enough to break out of poverty.

What interesting features are evident in the median household income intensity map in Figure 5.12 (d)?14

Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(a) Poverty rate
Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(b) Unemployment rate
Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(c) Homeownership rate
Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(d) Median household income, in thousands of USD
Figure 5.12: Intensity maps of US counties

5.9 Chapter review

5.9.1 Summary

Fluently working with numerical variables is an important skill for data analysts. In this chapter we have introduced different visualizations and numerical summaries applied to numeric variables. The graphical visualizations are even more descriptive when two variables are presented simultaneously. We presented scatterplots, dot plots, histograms, and box plots. Numerical variables can be summarized using the mean, median, quartiles, standard deviation, and variance.

5.9.2 Terms

The terms introduced in this chapter are presented in Table 5.5. If you’re not sure what some of these terms mean, we recommend you go back in the text and review their definitions. You should be able to easily spot them as bolded text.

Table 5.5: Terms introduced in this chapter.
average IQR standard deviation
bimodal left skewed symmetric
box plot mean tail
data density median third quartile
density plot multimodal transformation
deviation nonlinear unimodal
distribution outlier variability
dot plot percentile variance
first quartile point estimate weighted mean
histogram right skewed whiskers
intensity map robust statistics
interquartile range scatterplot

5.10 Exercises

Answers to odd-numbered exercises can be found in Appendix A.5.

  1. Mammal life spans. Data were collected on life spans (in years) and gestation lengths (in days) for 62 mammals. A scatterplot of life span versus length of gestation is shown below.15 (Allison and Cicchetti 1975)

     

    1. What type of an association is apparent between life span and length of gestation?

    2. What type of an association would you expect to see if the axes of the plot were reversed, i.e., if we plotted length of gestation versus life span?

    3. Are life span and length of gestation independent? Explain your reasoning.

     

  1. Associations. Indicate which of the plots show (a) a positive association, (b) a negative association, or (c) no association. Also determine if the positive and negative associations are linear or nonlinear. Each part may refer to more than one plot.

  1. Reproducing bacteria. Suppose that there is only sufficient space and nutrients to support one million bacterial cells in a petri dish. You place a few bacterial cells in this petri dish, allow them to reproduce freely, and record the number of bacterial cells in the dish over time. Sketch a plot representing the relationship between number of bacterial cells and time.
  1. Office productivity. Office productivity is relatively low when the employees feel no stress about their work or job security. However, high levels of stress can also lead to reduced employee productivity. Sketch a plot to represent the relationship between stress and productivity.
  1. Make-up exam. In a class of 25 students, 24 of them took an exam in class and 1 student took a make-up exam the following day. The professor graded the first batch of 24 exams and found an average score of 74 points with a standard deviation of 8.9 points. The student who took the make-up the following day scored 64 points on the exam.

    1. Does the new student’s score increase or decrease the average score?

    2. What is the new average?

    3. Does the new student’s score increase or decrease the standard deviation of the scores?

  1. Infant mortality. The infant mortality rate is defined as the number of infant deaths per 1,000 live births. This rate is often used as an indicator of the level of health in a country. The relative frequency histogram below shows the distribution of estimated infant death rates for 224 countries for which such data were available in 2014.16

     

    1. Estimate Q1, the median, and Q3 from the histogram.

    2. Would you expect the mean of this dataset to be smaller or larger than the median? Explain your reasoning.

     

  2. Days off at a mining plant. Workers at a particular mining site receive an average of 35 days paid vacation, which is lower than the national average. The manager of this plant is under pressure from a local union to increase the amount of paid time off. However, he does not want to give more days off to the workers because that would be costly. Instead he decides he should fire 10 employees in such a way as to raise the average number of days off that are reported by his employees. In order to achieve this goal, should he fire employees who have the most number of days off, least number of days off, or those who have about the average number of days off?

  3. Medians and IQRs. For each part, compare distributions A and B based on their medians and IQRs. You do not need to calculate these statistics; simply state how the medians and IQRs compare. Make sure to explain your reasoning. Hint: It may be useful to sketch dot plots of the distributions.

    1. A: 3, 5, 6, 7, 9; B: 3, 5, 6, 7, 20

    2. A: 3, 5, 6, 7, 9; B: 3, 5, 7, 8, 9

    3. A: 1, 2, 3, 4, 5; B: 6, 7, 8, 9, 10

    4. A: 0, 10, 50, 60, 100; B: 0, 100, 500, 600, 1000

  4. Means and SDs. For each part, compare distributions A and B based on their means and standard deviations. You do not need to calculate these statistics; simply state how the means and the standard deviations compare. Make sure to explain your reasoning. Hint: It may be useful to sketch dot plots of the distributions.

    1. A: 3, 5, 5, 5, 8, 11, 11, 11, 13; B: 3, 5, 5, 5, 8, 11, 11, 11, 20

    2. A: -20, 0, 0, 0, 15, 25, 30, 30; B: -40, 0, 0, 0, 15, 25, 30, 30

    3. A: 0, 2, 4, 6, 8, 10; B: 20, 22, 24, 26, 28, 30

    4. A: 100, 200, 300, 400, 500; B: 0, 50, 300, 550, 600

  5. Histograms and box plots. Describe (in words) the distribution in the histograms below and match them to the box plots.

  1. Air quality. Daily air quality is measured by the air quality index (AQI) reported by the Environmental Protection Agency. This index reports the pollution level and what associated health effects might be a concern. The index is calculated for five major air pollutants regulated by the Clean Air Act and takes values from 0 to 300, where a higher value indicates lower air quality. AQI was reported for a 356 days in 2022 in Durham, NC. The histogram below shows the distribution of the AQI values on these days.17

    1. Estimate the median AQI value of this sample.

    2. Would you expect the mean AQI value of this sample to be higher or lower than the median? Explain your reasoning.

    3. Estimate Q1, Q3, and IQR for the distribution.

    4. Would any of the days in this sample be considered to have an unusually low or high AQI? Explain your reasoning.

  1. Median vs. mean. Estimate the median for the 400 observations shown in the histogram, and note whether you expect the mean to be higher or lower than the median.

  1. Histograms vs. box plots. Compare the two plots below. What characteristics of the distribution are apparent in the histogram and not in the box plot? What characteristics are apparent in the box plot but not in the histogram?

  1. Facebook friends. Facebook data indicate that 50% of Facebook users have 100 or more friends, and that the average friend count of users is 190. What do these findings suggest about the shape of the distribution of number of friends of Facebook users? (Backstrom 2011)
  1. Distributions and appropriate statistics. For each of the following, state whether you expect the distribution to be symmetric, right skewed, or left skewed. Also specify whether the mean or median would best represent a typical observation in the data, and whether the variability of observations would be best represented using the standard deviation or IQR. Explain your reasoning.

    1. Number of pets per household.

    2. Distance to work, i.e., number of miles between work and home.

    3. Heights of adult males.

    4. Age at death.

    5. Exam grade on an easy test.

  1. Distributions and appropriate statistics. For each of the following, state whether you expect the distribution to be symmetric, right skewed, or left skewed. Also specify whether the mean or median would best represent a typical observation in the data, and whether the variability of observations would be best represented using the standard deviation or IQR. Explain your reasoning.

    1. Housing prices in a country where 25% of the houses cost below $350,000, 50% of the houses cost below $450,000, 75% of the houses cost below $1,000,000, and there are a meaningful number of houses that cost more than $6,000,000.

    2. Housing prices in a country where 25% of the houses cost below $300,000, 50% of the houses cost below $600,000, 75% of the houses cost below $900,000, and very few houses that cost more than $1,200,000.

    3. Number of alcoholic drinks consumed by college students in a given week. Assume that most of these students don’t drink since they are under 21 years old, and only a few drink excessively.

    4. Annual salaries of the employees at a Fortune 500 company where only a few high level executives earn much higher salaries than all the other employees.

    5. Gestation time in humans where 25% of the babies are born by 38 weeks of gestation, 50% of the babies are born by 39 weeks, 75% of the babies are born by 40 weeks, and the maximum gestation length is 46 weeks.

  1. TV watchers. College students in a statistics class were asked how many hours of television they watch per week, including online streaming services. This sample yielded an average of 8.28 hours, with a standard deviation of 7.18 hours. Is the distribution of number of hours students watch television weekly symmetric? If not, what shape would you expect this distribution to have? Explain your reasoning.
  1. Exam scores. The average on a history exam (scored out of 100 points) was 85, with a standard deviation of 15. Is the distribution of the scores on this exam symmetric? If not, what shape would you expect this distribution to have? Explain your reasoning.
  1. Midrange. The midrange of a distribution is defined as the average of the maximum and the minimum of that distribution. Is this statistic robust to outliers and extreme skew? Explain your reasoning.
  1. Oscar winners. The first Oscar awards for best actor and best actress were given out in 1929. The histograms below show the age distribution for all of the best actor and best actress winners from 1929 to 2019. Summary statistics for these distributions are also provided. Compare the distributions of ages of best actor and actress winners.18

     

    Mean SD n
    Best actor 43.8 8.8 92
    Best actress 36.2 11.9 92
  1. Stats scores. The final exam scores of twenty introductory statistics students, arranged in ascending order, as as follows: 57, 66, 69, 71, 72, 73, 74, 77, 78, 78, 79, 79, 81, 81, 82, 83, 83, 88, 89, 94. Suppose students who score above the 75th percentile on the final exam get an A in the class. How many students will get an A in this class?
  1. Income at the coffee shop. The first histogram below shows the distribution of the yearly incomes of 40 patrons at a college coffee shop. Suppose two new people walk into the coffee shop: one making $225,000 and the other $250,000. The second histogram shows the new income distribution. Summary statistics are also provided, rounded to the nearest whole number.

    n Min Q1 Median Mean Max SD
    Before 40 $60,679 $60,818 $65,238 $65,089 $69,885 $2,122
    After 42 $60,679 $60,838 $65,352 $73,299 $250,000 $37,321
    1. Would the mean or the median best represent what we might think of as a typical income for the 42 patrons at this coffee shop? What does this say about the robustness of the two measures?

    2. Would the standard deviation or the IQR best represent the amount of variability in the incomes of the 42 patrons at this coffee shop? What does this say about the robustness of the two measures?

  1. A new statistic. The statistic \(\frac{\bar{x}}{median}\) can be used as a measure of skewness. Suppose we have a distribution where all observations are greater than 0, \(x_i > 0\). What is the expected shape of the distribution under the following conditions? Explain your reasoning.

    1. \(\frac{\bar{x}}{median} = 1\)

    2. \(\frac{\bar{x}}{median} < 1\)

    3. \(\frac{\bar{x}}{median} > 1\)

  1. Commute times. The US census collects data on the time it takes Americans to commute to work, among many other variables. The histogram below shows the distribution of mean commute times in 3,142 US counties in 2017. Also shown below is a spatial intensity map of the same data.19

    1. Describe the numerical distribution and comment on whether a log transformation may be advisable for these data.

    2. Describe the spatial distribution of commuting times using the map.

  1. Hispanic population. The US census collects data on race and ethnicity of Americans, among many other variables. The histogram below shows the distribution of the percentage of the population that is Hispanic in 3,142 counties in the US in 2010. Also shown is a histogram of logs of these values.20

    1. Describe the numerical distribution and comment on why we might want to use log-transformed values in analyzing or modeling these data.

    2. What features of the distribution of the Hispanic population in US counties are apparent in the map but not in the histogram? What features are apparent in the histogram but not the map?

    3. Is one visualization more appropriate or helpful than the other? Explain your reasoning.

  1. NYC marathon winners. The histogram and box plots below show the distribution of finishing times for male and female (combined) winners of the New York City Marathon between 1970 and 2023.21

    1. What features of the distribution are apparent in the histogram and not the box plot? What features are apparent in the box plot but not in the histogram?

    2. What may be the reason for the bimodal distribution? Explain.

    3. Compare the distribution of marathon times for men and women based on the box plot shown below.

    1. The time series plot shown below is another way to look at these data. Describe what is visible in this plot but not in the others.


  1. Answers may vary. Scatterplots are helpful in quickly spotting associations relating variables, whether those associations come in the form of simple trends or whether those relationships are more complex.↩︎

  2. Consider the case where your vertical axis represents something “good” and your horizontal axis represents something that is only good in moderation. Health and water consumption fit this description: we require some water to survive, but consume too much and it becomes toxic and can kill a person.↩︎

  3. \(x_1\) corresponds to the interest rate for the first loan in the sample, \(x_2\) to the second loan’s interest rate, and \(x_i\) corresponds to the interest rate for the \(i^{th}\) loan in the dataset. For example, if \(i = 4,\) then we are examining \(x_4,\) which refers to the fourth observation in the dataset.↩︎

  4. The sample size was \(n = 50.\)↩︎

  5. Other ways to describe data that are right skewed: skewed to the right, skewed to the high end, or skewed to the positive end.↩︎

  6. The interest rates for individual loans.↩︎

  7. There might be two height groups visible in the dataset: the children (students) and the adults (teachers). That is, the data are probably bimodal.↩︎

  8. Figure 5.7 shows three distributions that look quite different, but all have the same mean, variance, and standard deviation. Using modality, we can distinguish between the first plot (bimodal) and the last two (unimodal). Using skewness, we can distinguish between the last plot (right skewed) and the first two. While a picture, like a histogram, tells a more complete story, we can use modality and shape (symmetry/skew) to characterize basic information about a distribution.↩︎

  9. Box plots were introducted by Mary Eleanor Spear who considered them to be a particular type of bar plot, see page 166 of Spear (1952). Mistakenly, box plots are often attributed to John Tukey who was the first person to call them “box-and-whisker plots.”↩︎

  10. Since \(Q_1\) and \(Q_3\) capture the middle 50% of the data and the median splits the data in the middle, 25% of the data fall between \(Q_1\) and the median, and another 25% falls between the median and \(Q_3.\)↩︎

  11. These visual estimates will vary a little from one person to the next: \(Q_1 \approx\) 8%, \(Q_3 \approx\) 14%, IQR \(\approx\) 14 - 8 = 6%.↩︎

  12. Mean is affected more than the median. Standard deviation is affected more than the IQR.↩︎

  13. If we are looking to simply understand what a typical individual loan looks like, the median is probably more useful. However, if the goal is to understand something that scales well, such as the total amount of money we might need to have on hand if we were to offer 1,000 loans, then the mean would be more useful.↩︎

  14. Answers will vary. There is some correspondence between high earning and metropolitan areas, where we can see darker spots (higher median household income), though there are several exceptions. You might look for large cities you are familiar with and try to spot them on the map as dark spots.↩︎

  15. The mammals data used in this exercise can be found in the openintro R package.↩︎

  16. The cia_factbook data used in this exercise can be found in the openintro R package.↩︎

  17. The pm25_2022_durham data used in this exercise can be found in the openintro R package.↩︎

  18. The oscars data used in this exercise can be found in the openintro R package.↩︎

  19. The county_complete data used in this exercise can be found in the usdata R package.↩︎

  20. The county_complete data used in this exercise can be found in the usdata R package.↩︎

  21. The nyc_marathon data used in this exercise can be found in the openintro R package.↩︎

中文

5  探索数值数据

本章重点通过汇总统计量和可视化来探索 数值型 使用汇总统计量和可视化来呈现数据。本章介绍的汇总和图形均使用统计软件创建;然而,由于这可能是你第一次接触这些概念,我们将在本章中花时间详细讲解如何创建它们。掌握本章内容对于理解本书其余部分介绍的方法和技术至关重要。

考虑 loan_amount 数据集中的 loan50 变量,它表示该数据集中 50 笔贷款中每笔贷款的规模。

该变量是数值型的,因为我们可以合理地讨论两笔贷款规模之间的数值差异。另一方面,电话区号和邮政编码不是数值型的,而是分类变量。

在本章中,我们将使用 loan50county 数据集应用数值方法,这些数据集已在 第 1.2 节中介绍过。如果你想回顾任一数据集中的变量,请参见表 表 1.4表 1.6.

county 数据可以在 usdata R 包和 loan50 数据可以在 openintro R 包中找到。

5.1 配对数据的散点图

一个 散点图 提供了两个数值型变量逐个案例的数据视图。在 图 1.2中,散点图被用于检验 county 数据集中住房自有率与多单元结构住房单元(例如公寓)所占百分比之间的关系。另一个散点图如 图 5.1所示,比较了借款人的总收入 total_income 与其借款金额 loan_amount 中针对 loan50 数据集。在任何散点图中,每个点代表一个案例。由于 loan50中有 50 个案例,因此 图 5.1.

A scatterplot with total income on the x-axis and loan amount on the y-axis. The relationship is moderately positive.
中有 50 个点。 loan50 数据集的最后五行。

查看 图 5.1,我们可以看到图左侧有许多收入低于 100,000 美元的借款人,而收入高于 250,000 美元的借款人只有少数几个。

A scatterplot with poverty rate on the x-axis and median household income on the y-axis. The relationship is negative and curvilinear. The bulk of the points fall with a poverty rate of 10% to 20% and a median household income of $25K to $75K.
图 5.2: county 数据集中家庭收入中位数与贫困率的散点图。数据来自 2017 年。图中还拟合了一个统计模型,以虚线显示。

图 5.2 展示了美国 3142 个县的家庭收入中位数与贫困率的关系图。关于这些变量之间的关系,我们能得出什么结论?


这种关系显然是 非线性的,如虚线所示。这与我们之前看到的散点图不同,那些散点图几乎(或完全没有)显示出趋势中的弯曲。

散点图能揭示数据的哪些信息,它们有什么用处?1

描述两个变量,使它们在散点图中呈现马蹄形的关联关系 \((\cap\)\(\frown).\)2

5.2 点图与均值

有时我们关注的是单个变量的分布。在这些情况下,点图提供了最基本的展示方式。 点图 是一种单变量散点图;一个使用50笔贷款利率数据的例子如 图 5.3.

A dot plot of interest rate (ranging from about 5% to 25%). The distribution is right skewed, and the mean is shown at an interest rate of about 11%.
图 5.3: loan50 数据集利率的点图。图中利率已四舍五入到最接近的百分比,分布的均值用一个红色三角形表示。

mean,通常被称为 平均值 ,是衡量数据 分布 中心的常用方法。要计算平均利率,我们将所有利率相加,然后除以观测值的数量。

样本均值通常标记为 \(\bar{x}.\) 字母 \(x\) 被用作所关注变量的通用占位符,而 \(x\) 上方的横线表示我们关注的是平均利率,对于这 50 笔贷款而言为 11.57%。将均值视为分布的平衡点是很有用的,在 图 5.3.

均值。

样本均值可以计算为观测值之和除以观测次数:

\[ \bar{x} = \frac{x_1 + x_2 + \cdots + x_n}{n} \]

考察均值的公式。 \(x_1\) 对应什么? \(x_2\)又对应什么?你能推断出 \(x_i\) 可能代表的一般含义吗?3

在这笔贷款样本中, \(n\) 是多少?4

loan50 数据集代表通过 Lending Club 发放的更大贷款总体的一个样本。我们可以用与样本均值相同的方式计算整个总体的均值。然而,总体均值有一个特殊的标记: \(\mu.\) 符号 \(\mu\) 是希腊字母 mu 并且表示总体中所有观测值的平均值。有时会使用下标,例如 \(_x,\) 来表示总体均值所指的变量,例如, \(\mu_x.\) 通常精确测量总体均值成本太高,所以我们常用样本均值来估计 \(\mu\) 使用样本均值, \(\bar{x}.\)

希腊字母 \(\mu\) 读作 mu,发音请听 这里.

虽然我们无法 计算 总体中所有贷款的平均利率,但我们可以使用样本数据来 估计 总体值。基于这 50 笔贷款的样本,对 \(\mu_x,\) 完整数据集中所有贷款的平均利率,合理的估计是多少?


样本均值 11.57 提供了对 \(\mu_x.\) 的粗略估计。虽然它并不完美,但这是我们最好的单一猜测 点估计 ,即所研究总体中所有贷款平均利率的点估计。在 第 11 章 及后续章节中,我们将开发一些工具来刻画点估计(如样本均值)的准确性。正如你可能已经猜到的,基于较大样本的点估计往往比基于较小样本的点估计更准确。

均值之所以有用,是因为它使我们能够将某个指标重新缩放或标准化为更易于解释和比较的形式。假设我们想了解一种新药在治疗哮喘发作方面是否比标准药物更有效。我们设置了一项针对1,500名成人的试验,其中500人接受新药,1,000人在对照组接受标准药物。该试验的结果总结于 表 5.1.

表 5.1:一项针对1500名哮喘患者的成人试验结果。
新药 标准药物
患者人数 500 1000
哮喘发作总次数 200 300

直接比较200次与300次哮喘发作的原始计数会让人以为新药更好,但这是组间人数不平衡造成的假象。

相反,我们应该比较每组中每位患者的平均哮喘发作次数:

  • 新药: \(200 / 500 = 0.4\) 次哮喘发作/人
  • 标准药物: \(300 / 1000 = 0.3\) 次哮喘发作/人

标准药物的平均每位患者哮喘发作次数低于治疗组(新药组)的平均值。

再举一个平均值有助于进行比较的例子。


Emilio 去年开了一辆售卖墨西哥卷饼的餐车,他的生意在过去 3 个月里已经趋于稳定。在这 3 个月期间,他工作了 625 小时,赚了 11,000 美元。Emilio 的平均时薪为评估他的创业是否值得(至少从财务角度来看)提供了一个有用的统计量:

\[ \frac{\$11000}{625\text{ hours}} = \$17.60\text{ per hour} \]

通过了解自己的平均时薪,Emilio 现在把收入换算成了一个标准单位,这样更容易与他可能考虑的许多其他工作进行对比。

假设我们想计算美国的人均平均收入。为此,我们可能首先想到对 county 数据集中 3,142 个县的人均收入取平均值。有没有更好的方法?


county 数据集的特殊之处在于,每个县实际上代表许多个人。如果我们只是对 income 变量取平均,就会在计算中把拥有 5,000 名居民和 5,000,000 名居民的县同等对待。相反,我们应该先计算每个县的总收入,把所有县的总收入加起来,再除以所有县的人口总数。如果我们用 county 数据完成这些步骤,会发现美国的人均收入为 30,861 美元。而如果我们计算的是各县人均收入的 简单 平均值,结果只有 26,093 美元!

这个例子使用了所谓的 加权平均数。有关此主题的更多信息,请查阅以下关于 加权平均数.

5.3 的在线补充材料。直方图与形状

点图显示每个观测值的确切数值。它们适用于小型数据集,但在样本较大时会变得难以阅读。与其显示每个观测值的数值,我们更倾向于把数值视为属于一个 分箱。例如,在 loan50 数据集中,我们创建了一个计数表,统计利率在 5.0% 到 7.5% 之间的贷款数量,然后是利率在 7.5% 到 10.0% 之间的贷款数量,依此类推。落在分箱边界上的观测值(例如 10.00%)被归入较低的分箱。该统计表显示在 表 5.2中,分箱计数以条形图的形式绘制在 图 5.4 中,这种图被称为 直方图。请注意,该直方图类似于 图 5.3.

中所示堆叠点图的一个分箱更细密的版本。 表 5.2:利率数据分箱计数。
利率 频数
(5% - 7.5%] 11
(7.5% - 10%] 15
(10% - 12.5%] 8
(12.5% - 15%] 4
(15% - 17.5%] 5
(17.5% - 20%] 4
(20% - 22.5%] 1
(22.5% - 25%] 1
(25% - 27.5%] 1
A histogram of interest rate (ranging from about 5% to 25%). The distribution is right skewed.
图 5.4:利率直方图。该分布明显右偏。

直方图提供了 数据密度的视图。较高的条形表示数据相对更常见的位置。例如,数据集中利率在 5% 到 10% 之间的贷款远多于利率在 20% 到 25% 之间的贷款。这些条形使我们能够轻松看出数据密度随利率变化的情况。

直方图对于理解数据分布的形状尤其方便。 图 5.4 表明大多数贷款的利率低于 15%,而只有少数贷款的利率高于 20%。当一个变量的分布像这样向右侧逐渐减少并具有较长的右侧 尾部,则称该形状为 右偏.5

A density plot of interest rate (ranging from about 5% to 25%). The distribution is right skewed.
图 5.5:利率的密度图。同样,该分布明显右偏。

图 5.5 展示了一个 密度图 ,它是一种平滑处理后的直方图。绘制密度图的技术细节(即如何精确地对直方图进行平滑处理)超出了本书的范围,但你会注意到,观测值的形状、尺度和离散程度在直方图和密度图中的呈现方式是相似的。

具有相反特征——左侧有一条细长的尾巴——的变量被称为 左偏。我们也说这样的分布具有较长的左尾。在两个方向上尾部的拖尾大致相等的变量被称为 对称.

当数据向一个方向拖尾时,该分布具有一个长尾

。如果分布具有较长的左尾,则它是左偏的;如果分布具有较长的右尾,则它是右偏的。 图 5.3 除了均值(因为它已被标注)之外,你还能在 图 5.4?6

的点图中看到哪些在直方图中看不到的信息? 的一个定义 在分布中表现为一个显著的峰。直方图 interest_rate.

中只有一个显著的峰。 的一个定义 众数 (数学课上有时会讲授)是数据集中出现次数最多的值。然而,对于许多真实世界的数据集,数据集中常常 没有

图 5.6 相同值的观测,这使得该定义在数据分析中并不实用。 单峰, 双峰多峰多峰分布

Three separate histograms on fabricated data. The first histogram shows a unimodal distribution, the second histogram shows a bimodal distribution, and the third histogram shows a multimodal distribution.
。任何具有超过两个显著峰的分布都称为多峰分布。注意,单峰分布中有一个显著峰,还有一个不太显著的峰未被计入,因为它与其相邻的区间仅相差几个观测值。

图 5.4 图 5.6:只计算显著峰,这些分布(从左到右)分别为单峰、双峰和多峰。注意,左图是单峰的,因为我们只计算显著峰,而不是任何峰。


显示利率只有一个显著的众数。该分布是单峰、双峰还是多峰分布? uni 代表 1(想想 unicycle,独轮车),而 bi 代表 2(想想 bicycle,自行车)。

在某所小学测量了低年级学生和成年教师的身高。你预计这个身高数据集中会有多少个众数?7

寻找众数并不是要为分布中众数的个数找到一个明确且正确的答案,这也是本书没有对 明显 进行严格定义的原因。这一考察最重要的部分是更好地理解你的数据。

5.4 方差与标准差

均值被用来描述变量的中心,而数据中的 变异性 同样重要。这里我们介绍两种变异性的度量:方差和标准差。尽管它们的公式用手计算比较繁琐,但这两者在数据分析中都非常有用。标准差是两者中较容易理解的,因为它大致描述了典型观测值距离均值有多远。

我们把观测值与其均值之间的距离称为它的 偏差。以下是 \(1^{st},\) \(2^{nd},\) \(3^{rd},\)\(50^{th}\) 观测值在 interest_rate 变量:

\[ \begin{aligned} x_1 - \bar{x} &= 10.9 - 11.57 = -0.67 \\ x_2 - \bar{x} &= 9.92 - 11.57 = -1.65 \\ x_3 - \bar{x} &= 26.3 - 11.57 = 14.73 \\ &\vdots \\ x_{50} - \bar{x} &= 6.08 - 11.57 = -5.49 \\ \end{aligned} \]

如果我们将这些偏差平方后取平均值,结果就等于样本 方差,记作 \(s^2\):

\[ s^2 = \frac{(-0.67)^2 + (-1.65)^2 + (14.73)^2 + \cdots + (-5.49)^2}{50 - 1} = \frac{0.45 + 2.72 + \cdots + 30.14}{49} = 25.52 \]

我们除以 \(n - 1,\) 而不是除以 \(n,\) 来计算样本方差。这里有一些数学上的细微差别,但最终结果是这样做会使该统计量更加可靠和有用。

注意,对偏差进行平方有两个作用。第一,它使较大的值相对变得更大。第二,它消除了所有负号。

标准差。

样本标准差可以计算为:每个值与均值之差的平方之和除以观测值个数减一,再取平方根:

\[s = \sqrt{\frac{\sum_{i=1}^n (x_i - \bar{x})^2}{n-1}}\]

标准差 定义为方差的平方根:

\[s = \sqrt{25.52} = 5.05\]

虽然经常省略,但可以在方差和标准差上加上下标 \(_x\) ,即 \(s_x^2\)\(s_x^{},\) 如果这有助于提醒我们这些是由 \(x_1,\) \(x_2,\) …, \(x_n.\)

方差和标准差。

方差是与均值距离的平方的平均值。标准差是方差的平方根。在考虑数据偏离均值的分布程度时,标准差非常有用。

标准差表示观测值偏离均值的典型程度。通常约68%的数据位于均值的一个标准差范围内,约95%位于两个标准差范围内。然而,这些百分比并不是严格的规则。

与均值一样,总体的方差和标准差有专门的符号: \(\sigma^2\) 表示方差, \(\sigma\) 表示标准差。

希腊字母 \(\sigma\) 读作 sigma,发音请听 这里.

对分布形状的良好描述应包括峰态(单峰、双峰等)以及分布是对称的还是偏向一侧偏斜的。以 图 5.7 为例,解释为什么这样的描述很重要。8

A histogram of the right-skewed variable, interest rates. Grey shading indicates the empirical rule cutoffs of one and two standard deviations. Because the variable is right-skewed, the empirical rule ranges do not capture the desired amoung of data, 68% and 95% respectively.

对于利率变量,50笔贷款中有34笔(68%)的利率位于均值的一个标准差范围内,50笔贷款中有48笔(96%)的利率位于两个标准差范围内。通常约68%的数据位于均值的一个标准差范围内,95%位于两个标准差范围内,但这远非硬性规则。
Three histograms of fabricated data with empirical rule shading of one and two standard deviations superimposed. The bimodal and right skewed histogram demonstrate that the empirical rule is not a good approximation. The empirical rule fits well to the unimodal bell-shaped distribution.
图5.7:三个均值(0)和标准差(1)相同的不同总体分布。

使用 interest_rate 中的直方图描述 图 5.4变量的分布。描述应包含分布的中心、变异性和形状,并且应结合具体情境。同时指出任何特别异常的个案。


利率的分布是单峰且向高端偏斜的。许多利率接近11.57%的均值,大多数位于均值的一个标准差(5.05%)范围内。样本中有少数特别高的利率超过20%。

在实践中,方差和标准差有时被用作达到目的的手段,而这个“目的”是能够准确估计与样本统计量相关的不确定性。例如,在 第13章 标准差用于帮助我们理解样本均值在样本之间的变化程度的计算中。

5.5 箱线图、四分位数与中位数

一个 箱线图 使用五个统计量来概括数据集,同时识别异常观测值。 图 5.8 提供了 interest_rate 数据集中的 loan50 数据集中。9

Two plots showing the same variable, interests rates. The top image is a dot plot, the bottom image is a box plot. Both images re-establish that the distribution of interest rates are right skewed.
(a) 点图
Two plots showing the same variable, interests rates. The top image is a dot plot, the bottom image is a box plot. Both images re-establish that the distribution of interest rates are right skewed.
(b) 箱线图
图5.8:来自 loan50 数据集的最后五行。

的利率分布 中位数中位数 loan50 ,它将数据分成两半。50%的数据低于该值,50%的数据高于该值。由于在 \(50^{th}\) 数据集中有50个观测值(偶数),中位数被定义为最接近 表 5.3 百分位数的两个观测值的平均值。 \(25^{th}\)\(26^{th}\) 按升序显示了所有利率。我们可以看到,这两个值都是9.93,对应于 图 5.8 (b) 中的箱线图.

表 5.3:来自 loan50 数据集的利率,按升序排列。
1 2 3 4 5 6 7 8 9 10
1 5.31 5.31 5.32 6.08 6.08 6.08 6.71 6.71 7.34 7.35
10 7.35 7.96 7.96 7.96 7.97 9.43 9.43 9.44 9.44 9.44
20 9.92 9.92 9.92 9.92 9.93 9.93 10.42 10.42 10.90 10.90
30 10.91 10.91 10.91 11.98 12.62 12.62 12.62 14.08 15.04 16.02
40 17.09 17.09 17.09 18.06 18.45 19.42 20.00 21.45 24.85 26.30

当观测数为奇数时,恰好有一个观测值将数据分成两半,在这种情况下,该观测值即为中位数(无需取平均)。

中位数:位于中间的数值。

如果数据按从小到大排序, 中位数 就是正中间的观测值。如果观测数为偶数,中间会有两个值,中位数取它们的平均值。

构建箱线图的第二步是画一个矩形来表示数据中间的 50%。矩形的长度称为 四分位距,或 IQR (简称)。与标准差一样,它是数据变异性的度量。数据变异性越大,标准差和 IQR 往往越大。矩形的两个边界分别称为 第一四分位数 (即 \(25^{th}\) 百分位数,即 25% 的数据低于该值)和 第三四分位数 (即 \(75^{th}\) 百分位数,也就是说75%的数据低于该值),它们通常分别标记为 \(Q_1\)\(Q_3,\)

四分位距(IQR)。

IQR四分位距是箱线图中箱子的长度。它的计算公式为 \(IQR = Q_3 - Q_1,\) ,其中 \(Q_1\)\(Q_3\) 分别是 \(25^{th}\)\(75^{th}\) 百分位数。

一个 \(\alpha\) 百分位数 是一个数值,有 \(\alpha\)%的观测值低于它, \(100-\alpha\)%的观测值高于它。例如,SAT分数的 \(90^{th}\) 百分位数是指这样一个SAT分数值:有90%的学生低于该值,10%的学生高于该值。

有多少百分比的数据位于 \(Q_1\) 和中位数之间?有多少百分比位于中位数和 \(Q_3\)?10

之间?从箱子向外延伸的 须线 试图捕捉箱线图以外的数据。箱线图的须延伸至数据中的最小值和最大值,除非存在被认为异常高或异常低的点,这些点被箱线图识别为潜在的 离群点 。这些点在箱线图上用圆点标注。标注离群点的目的——而不是将须延伸至观测到的最小值和最大值——是为了帮助识别那些看起来与其余数据距离异常遥远的观测值。判断某个数据点是否为离群点有多种公式,不同的统计软件使用不同的公式。一个常用的公式是:任何超出 \(1.5\times IQR\) (距第一四分位数或第三四分位数的距离)的观测值都被视为离群点。从某种意义上说,箱体就像箱线图的身体,而须就像它的手臂,试图触及其余的数据,直到离群点为止。

离群点是极端的。

一个 离群值 是指相对于其余数据显得极端的观测值。检查数据中的离群点有许多有用的目的,包括

  • 识别分布中的严重偏斜,
  • 识别可能的数据收集或数据录入错误,以及
  • 提供对数据有趣特性的洞察。

但请记住,有些数据集本身具有较长的偏斜,离群点并不 代表数据集中存在任何问题。

使用 图 5.8 (b) 中的箱线图, 估计 \(Q_1,\) \(Q_3,\) 的值和 interest_rate 的 IQR,在 loan50 数据集中。11

5.6 稳健统计

观测值 26.3% 对 样本统计量 ,针对 interest_rate 数据集有何影响?如果这笔贷款只有 15%,会发生什么?如果 26.3% 处的观测值更大,比如 35%,这些汇总统计量又会怎样变化?三种假设情景与原始数据一并绘制在 图 5.9中,各情景下的样本统计量计算在 表 5.4.

表 5.4:比较原始利率数据中极端观测值变化时,中位数、IQR、均值和标准差的变化。
稳健
不稳健
情景 中位数 IQR 平均数 标准差
原始数据 9.93 5.75 11.6 5.05
将26.3%移至15% 9.93 5.75 11.3 4.61
将26.3%移至35% 9.93 5.75 11.7 5.68
Three dot plots are displayed where a single point is highlighted. In the top plot is the original data where the highlighted point is the largest value, at 26.3%. The second plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 15%. The third plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 35%. The corresponding change in statistics are given in @tbl--robustOrNotTable.
(a) 原始数据
Three dot plots are displayed where a single point is highlighted. In the top plot is the original data where the highlighted point is the largest value, at 26.3%. The second plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 15%. The third plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 35%. The corresponding change in statistics are given in @tbl--robustOrNotTable.
(b) 将26.3%移至15%
Three dot plots are displayed where a single point is highlighted. In the top plot is the original data where the highlighted point is the largest value, at 26.3%. The second plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 15%. The third plot shows the distribution of the interest rate data after moving the highlighted point from 26.3% to 35%. The corresponding change in statistics are given in @tbl--robustOrNotTable.
(c) 将26.3%移至35%
图5.9:原始利率数据及两个修改后数据集的点图。

哪个更容易受极端观测值影响,均值还是中位数?标准差还是四分位距更容易受极端观测值影响?12

中位数和四分位距被称为 稳健统计 ,因为极端观测值对它们的数值影响很小:移动最极端的值通常对这些统计量几乎没有影响。另一方面,均值和标准差更容易受极端观测值变化的影响,这在某些情况下可能很重要。

在三种情形下,中位数和四分位距在 表 5.4中都没有变化。为什么会这样?


中位数和四分位距只对 \(Q_1,\) 中位数附近的数值敏感,而 \(Q_3.\) 。由于这三个数据集中这些区域的数值是稳定的,因此中位数和四分位距的估计值也是稳定的。

对于“均值和中位数哪个更好?”这个问题,答案你可能不会感到惊讶: 视情况而定。这两种统计量衡量的是不同的东西,因此它们的使用取决于分析的具体情境。请考虑以下场景:

  • 衡量每位客户的平均利润更好,还是衡量每位客户利润的中位数更好?
    • 如果关注的是公司的整体利润率,那么均值是评估公司整体状况的更好指标。公司每位客户利润的中位数可能为正,但公司整体仍可能亏损。
    • 如果关注的是了解典型客户的利润,可能是为了了解公司利润的增长空间,那么每位客户利润的中位数能更好地反映单个客户的利润情况。
  • 如果你运营一款应用,想知道应用在客户手机上打开需要多长时间,你是想要平均时间还是中位数时间?
    • 均值有助于了解打开应用所浪费的总时间。
    • 中位数则能反映典型用户的使用体验。
    • 然而,如果该应用对50%的用户启动时间少于5毫秒,但对10%的用户启动时间超过10秒,那么中位数就无法提供你所需的信息。在这种情况下,你可能需要一个较高的百分位数,例如第95百分位数。

数据集中贷款金额的分布 loan50 呈右偏态,少数大额贷款延伸至右尾。如果你想了解典型的贷款规模,你应该更关注均值还是中位数?13

无论选择哪种集中趋势统计量(均值或中位数),对于大多数分析而言,重要的不仅仅是考虑集中趋势。上百分位数和下百分位数、IQR或标准差等其他统计量可以提供关于观测值变异性的信息。而通过图形方式将数据可视化,通常能提供丰富的信息,有助于全面理解与研究问题相关的数据全貌。

5.7 数据变换

当数据严重偏态时,我们有时会对其进行变换,使其更易于建模。 图 5.10 (a)图 5.10 (b) 呈现右偏分布:美国所有县的失业人口百分比分布和人口分布。人口分布比失业百分比分布偏斜得更厉害,因此对数变换使分布形状产生了更大的变化。

考虑图中所示的县人口直方图 图 5.10 (c),它呈现出极端的偏斜。该图的哪些特征使其失去了实用性?


几乎所有数据都落在最左侧的区间中,极端的偏斜掩盖了低数值处许多潜在有趣的细节。

Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(a) 失业百分比
Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(b) 对数\(_{10}\)变换后的失业百分比
Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(c) 人口
Two pairs of histograms are shown. In the first pair of histograms, percentage of unemployed in all US counties is shown next to the log-10 transformed percentage of unemployed. The raw percent unemployed shows a right-skewed distribution, and the log-10 transformed data is symmetric and bell-shaped. In the second pair of histograms, population of each US county is shown next to the log-10 transformed population. The raw population is extremely right-skewed, and the log-10 transformed data is reasonably symmetric and bell-shaped.
(d) 对数\(_{10}\)变换后的人口
图 5.10:美国所有县的失业百分比、人口及其对数变换版本的直方图。对于变换后变量的图,x 值对应于 10 的幂,例如 x 轴上的 1 对应于 \(10^1 =\) 10,x 轴上的 5 对应于 \(10^5=\) 100,000。数据来自 2017 年。

有一些标准变换可能对强烈右偏的数据有用,这类数据大部分为正值但聚集在零附近。一种 变换 是使用某种函数对数据进行重新缩放。例如,绘制失业率(以10为底的对数)与县人口对数的图形,会得到 图 5.10 (b)中的新直方图。变换后的数据是对称的,任何潜在的异常值看起来都不如原始数据集中那么极端。通过抑制异常值和极端偏态,变换通常能让我们更容易为数据构建统计模型。

变换也可以应用于散点图中的一个或两个变量。2010年至2017年人口变化与2010年人口的关系散点图如 图 5.11 (a)所示。由于人口变量的偏态非常严重,很难从中解读出任何有趣的模式。然而,如果我们对人口变量应用对数\(_{10}\) 变换,如 图 5.11 (b)所示,变量之间的正相关关系便显现出来。事实上,当我们在 第 7 章.

A pair of scatterplots is given. In both plots the y-axis is population change. In the first plot, the x-axis is given by the raw variable population before change, and most of the points are quite small, obscuring any  x-y relationship. In the second plot, the x-axis is given by the transformed variable log-10 of the population before change. The relationship between log-10 population before change and population change is seen to be moderately strong, positive, and linear.
(a) 人口变化
A pair of scatterplots is given. In both plots the y-axis is population change. In the first plot, the x-axis is given by the raw variable population before change, and most of the points are quite small, obscuring any  x-y relationship. In the second plot, the x-axis is given by the transformed variable log-10 of the population before change. The relationship between log-10 population before change and population change is seen to be moderately strong, positive, and linear.
(b) 对数\(_{10}\)变换后的人口变化
图 5.11:人口变化及对数\(_{10}\)变换后的人口变化与变化前人口的散点图。

对数以外的变换也很有用。例如,平方根 \((\sqrt{\text{original observation}})\) 和倒数 \(\bigg ( \frac{1}{\text{original observation}} \bigg )\) 是数据科学家常用的方法。数据变换的常见目标是:以不同的方式查看数据结构、减少偏度、辅助建模,或使散点图中的非线性关系线性化。

5.8 数据映射

county 数据集提供了许多数值变量,我们可以用点图、散点图或箱线图来绘制它们,但这些图可能会忽略数据作为地理数据的真实特性。当我们遇到地理数据时,应该创建 强度图,用颜色来显示某个变量的较高值和较低值。 图 5.12 展示了贫困率(百分比,poverty)、失业率(百分比,unemployment_rate)、住房自有率(百分比,homeownership)以及家庭收入中位数(以千美元计,median_hh_income)的强度图。颜色键标明了哪些颜色对应哪些数值。强度图通常不太适合获取某个县的精确数值,但对于观察地理趋势以及提出有趣的研究问题或假设非常有帮助。

图 的贫困率和失业率强度图中,可以看出哪些有趣的特征?图 5.12 (a)?


5.12 (b)

贫困率显然在几个地区较高。值得注意的是,深南部地区的贫困率较高,亚利桑那州和新墨西哥州的大部分地区也是如此。在新奥尔良以北不远的密西西比河泛滥平原以及肯塔基州的一大片区域,贫困率明显较高。

失业率呈现类似的趋势,我们可以看到这两个变量之间的对应关系。事实上,较高的失业率与贫困率密切相关是合理的。比较这两幅图时有一个突出的观察结果:贫困率远高于失业率,这意味着许多人虽然有工作,但收入不足以摆脱贫困。 图 在家庭收入中位数强度图(图?14

Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(a) 贫困率
Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(b) 失业率
Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(c) 自有住房率
Four intensity map (also called heatmaps) of the United States. Each county is colored by the value of a variables. In the first plot, the county is colored by the poverty rate which is higher in the south and parts of the midwest. In the second plot, the county is colored by the unemployment rate which seems higher in the southwest and parts of the post-industrial Midwest. In the third plot, the county is colored by home ownership rate which is lowest on the west coast. In the fourth and last plot, the county is colored by median household income which is highest in the Bay Area and along the New England coast.
(d) 家庭收入中位数,单位为千美元
图 5.12:美国各县的强度地图

5.9 本章复习

5.9.1 小结

熟练处理数值变量是数据分析师的一项重要技能。在本章中,我们介绍了应用于数值变量的不同可视化方法和数值汇总。当同时呈现两个变量时,图形化可视化更具描述性。我们介绍了散点图、点图、直方图和箱线图。数值变量可以使用均值、中位数、四分位数、标准差和方差进行汇总。

5.9.2 术语

本章中介绍的术语列于 表 5.5。如果您不确定其中一些术语的含义,我们建议您回到正文中复习它们的定义。您应该能够很容易地发现它们是 粗体文本.

表 5.5:本章介绍的术语。
平均值 IQR 标准差
双峰 左偏 对称
箱线图 mean 尾部
数据密度 中位数 第三四分位数
密度图 多峰 变换
偏差 非线性的 单峰
分布 离群值 变异性
点图 百分位数 方差
第一四分位数 点估计 加权平均数
直方图 右偏 须线
强度图 稳健统计
四分位距 散点图

5.10 练习

奇数编号习题的答案见 附录 A.5.

  1. 哺乳动物的寿命。 数据收集了62种哺乳动物的寿命(以年为单位)和妊娠期长度(以天为单位)。下图显示了寿命与妊娠期长度的散点图。15 (Allison 和 Cicchetti 1975)

     

    1. 寿命与妊娠期长度之间呈现出什么类型的关联?

    2. 如果坐标轴反转,即绘制妊娠期长度与寿命的关系图,你预期会看到什么类型的关联?

    3. 寿命与妊娠期长度是否独立?请解释你的理由。

     

  1. 关联。 指出哪些图显示 (a) 正关联,(b) 负关联,或 (c) 无关联。同时判断正关联和负关联是线性的还是非线性的。每个小题可能涉及不止一个图。

  1. 繁殖的细菌。 假设培养皿中的空间和营养仅足以支持一百万个细菌细胞。你将几个细菌细胞放入这个培养皿中,让它们自由繁殖,并记录培养皿中细菌细胞数量随时间的变化。请绘制一个表示细菌细胞数量与时间关系的图。
  1. 办公效率。 当员工对工作或工作保障毫无压力时,办公效率相对较低。然而,高水平的压力也会导致员工效率下降。请绘制一个表示压力与效率关系的图。
  1. 补考。 在一个 25 名学生的班级中,24 名学生在课堂上参加了一次考试,1 名学生在第二天参加了补考。教授批改了第一批 24 份试卷,发现平均分为 74 分,标准差为 8.9 分。第二天参加补考的学生得了 64 分。

    1. 这名新学生的分数是提高还是降低了平均分?

    2. 新的平均分是多少?

    3. 这名新学生的分数是提高还是降低了分数的标准差?

  1. 婴儿死亡率。 婴儿死亡率定义为每1,000名活产婴儿中的婴儿死亡人数。该比率常被用作衡量一个国家健康水平的指标。下面的相对频率直方图显示了2014年有相关数据的224个国家的估计婴儿死亡率的分布。16

     

    1. 从直方图中估计Q1(第一四分位数)、中位数和Q3(第三四分位数)。

    2. 你认为该数据集的均值会比中位数小还是大?请解释你的理由。

     

  2. 某采矿厂的休假天数。 某采矿场的工人平均享有35天带薪休假,低于全国平均水平。该厂经理受到当地工会要求增加带薪休假天数的压力。然而,他不想给工人更多休假天数,因为那样成本很高。于是他决定以某种方式解雇10名员工,从而提高员工报告的平均休假天数。为了实现这一目标,他应该解雇休假天数最多的员工、最少的员工,还是休假天数接近平均水平的员工?

  3. 中位数和四分位距。 对每一小题,根据中位数和四分位距比较分布A和B。你不需要计算这些统计量;只需说明中位数和四分位距如何比较即可。请务必解释你的理由。 提示: 画出这些分布的点图可能会有帮助。

    1. A: 3, 5, 6, 7, 9; B: 3, 5, 6, 7, 20

    2. A: 3, 5, 6, 7, 9; B: 3, 5, 7, 8, 9

    3. A: 1, 2, 3, 4, 5; B: 6, 7, 8, 9, 10

    4. A: 0, 10, 50, 60, 100; B: 0, 100, 500, 600, 1000

  4. 均值和标准差。 对每个部分,根据均值和标准差比较分布 A 和 B。你不需要计算这些统计量;只需说明均值和标准差如何比较。请务必解释你的理由。 提示: 画出这些分布的点图可能会有帮助。

    1. A: 3, 5, 5, 5, 8, 11, 11, 11, 13; B: 3, 5, 5, 5, 8, 11, 11, 11, 20

    2. A: -20, 0, 0, 0, 15, 25, 30, 30; B: -40, 0, 0, 0, 15, 25, 30, 30

    3. A: 0, 2, 4, 6, 8, 10; B: 20, 22, 24, 26, 28, 30

    4. A: 100, 200, 300, 400, 500; B: 0, 50, 300, 550, 600

  5. 直方图和箱线图。 用文字描述下面直方图中的分布,并将它们与箱线图匹配。

  1. 空气质量。 每日空气质量由美国环境保护署报告的空气质量指数(AQI)来衡量。该指数报告污染水平以及可能引发的健康影响。该指数针对《清洁空气法》所管制的五种主要空气污染物进行计算,取值范围为0到300,数值越高表示空气质量越差。2022年北卡罗来纳州达勒姆市报告了356天的AQI。下面的直方图显示了这些天AQI值的分布。17

    1. 估计该样本的AQI中位数。

    2. 你认为该样本的AQI均值会高于还是低于中位数?请解释你的理由。

    3. 估计该分布的Q1、Q3和IQR。

    4. 该样本中是否有任何一天的AQI可被视为异常低或异常高?请解释你的理由。

  1. 中位数与均值。 估计直方图中所示的400个观测值的中位数,并说明你预期均值会高于还是低于中位数。

  1. 直方图与箱线图。 比较下面的两个图。分布的哪些特征在直方图中明显而在箱线图中不明显?哪些特征在箱线图中明显而在直方图中不明显?

  1. Facebook好友。 Facebook数据显示,50%的Facebook用户拥有100个或更多好友,且用户的平均好友数为190。这些发现表明Facebook用户好友数分布的形状是怎样的? (Backstrom 2011)
  1. 分布及相应的统计量。 针对以下每种情况,说明你预期其分布是对称的、右偏的还是左偏的。同时说明均值还是中位数能更好地代表数据中的典型观测值,以及用标准差还是四分位距(IQR)能更好地表示观测值的变异性。请解释你的理由。

    1. 每户宠物数量。

    2. 上班距离,即工作地点与家之间的英里数。

    3. 成年男性的身高。

    4. 死亡年龄。

    5. 简单考试的考试成绩。

  1. 分布及相应的统计量。 针对以下每种情况,说明你预期其分布是对称的、右偏的还是左偏的。同时说明均值还是中位数能更好地代表数据中的典型观测值,以及用标准差还是四分位距(IQR)能更好地表示观测值的变异性。请解释你的理由。

    1. 某个国家的房价:25%的房屋价格低于350,000美元,50%的房屋价格低于450,000美元,75%的房屋价格低于1,000,000美元,并且有相当数量的房屋价格超过6,000,000美元。

    2. 某个国家的房价:25%的房屋价格低于300,000美元,50%的房屋价格低于600,000美元,75%的房屋价格低于900,000美元,只有极少数房屋价格超过1,200,000美元。

    3. 大学生在一周内饮用的酒精饮料数量。假设这些学生中大多数因为未满21岁而不饮酒,只有少数人饮酒过量。

    4. 某财富500强公司员工的年薪,其中只有少数高层管理人员的薪水远高于其他所有员工。

    5. 人类的妊娠期:25%的婴儿在妊娠38周及之前出生,50%的婴儿在39周及之前出生,75%的婴儿在40周及之前出生,最长妊娠期为46周。

  1. 看电视的人。 某统计学课上的大学生被问及他们每周看多少小时电视,包括在线流媒体服务。该样本的平均值为8.28小时,标准差为7.18小时。学生每周看电视小时数的分布是对称的吗?如果不是,你预期该分布会呈什么形状?请解释你的理由。
  1. 考试成绩。 某次历史考试(满分100分)的平均分为85分,标准差为15分。这次考试分数的分布是对称的吗?如果不是,你预期该分布会呈什么形状?请解释你的理由。
  1. 中距。中列数 分布的中列数定义为该分布的最大值与最小值的平均值。这个统计量对异常值和极端偏态是否稳健?请解释你的理由。
  1. 奥斯卡获奖者。 第一届奥斯卡最佳男主角和最佳女主角奖于1929年颁发。下面的直方图显示了1929年至2019年所有最佳男主角和最佳女主角获奖者的年龄分布。同时还提供了这些分布的汇总统计量。请比较最佳男主角和最佳女主角获奖者年龄的分布。18

     

    平均数 标准差 n
    最佳男主角 43.8 8.8 92
    最佳女主角 36.2 11.9 92
  1. 统计学成绩。 二十名统计学导论课学生的期末考试成绩按升序排列如下:57, 66, 69, 71, 72, 73, 74, 77, 78, 78, 79, 79, 81, 81, 82, 83, 83, 88, 89, 94。假设期末考试成绩高于第75百分位数的学生在该课程中获得A。有多少学生会在这门课程中获得A?
  1. 咖啡店的收入。 下面的第一个直方图显示了一所大学咖啡店40位顾客年收入分布。假设两位新顾客走进咖啡店:一位年收入为$225,000,另一位为$250,000。第二个直方图显示了新的收入分布。同时还提供了汇总统计量,四舍五入到最接近的整数。

    n 最小值 Q1 中位数 平均数 最大值 标准差
    之前 40 $60,679 $60,818 $65,238 $65,089 $69,885 $2,122
    之后 42 $60,679 $60,838 $65,352 $73,299 $250,000 $37,321
    1. 对于这家咖啡店的42位顾客,平均数和中位数哪个更能代表我们通常认为的典型收入?这对两种度量方法的稳健性说明了什么?

    2. 对于这家咖啡店42位顾客的收入变异程度,标准差和四分位距哪个更能代表其变异性?这对两种度量方法的稳健性说明了什么?

  1. 一个新的统计量。 统计量 \(\frac{\bar{x}}{median}\) 可以用作偏度的度量。假设我们有一个所有观测值都大于0的分布,即 \(x_i > 0\)。在以下条件下,该分布的预期形状是什么?请解释你的理由。

    1. \(\frac{\bar{x}}{median} = 1\)

    2. \(\frac{\bar{x}}{median} < 1\)

    3. \(\frac{\bar{x}}{median} > 1\)

  1. 通勤时间。 美国人口普查收集了美国人通勤上班所需时间的数据,以及许多其他变量的数据。下面的直方图显示了2017年美国3,142个县平均通勤时间的分布。下面还展示了相同数据的空间强度图。19

    1. 描述其数值分布,并评论对这些数据进行对数变换是否合适。

    2. 利用地图描述通勤时间的空间分布。

  1. 西班牙裔人口。 美国人口普查收集美国人的种族和民族数据,以及许多其他变量。下面的直方图显示了2010年美国3,142个县人口中西班牙裔百分比的分布。同时还显示了这些数值的对数的直方图。20

    1. 描述数值分布,并说明为什么在分析或建模这些数据时我们可能希望使用对数变换后的数值。

    2. 美国各县西班牙裔人口分布的哪些特征在地图上明显而在直方图中不明显?哪些特征在直方图中明显而在地图上不明显?

    3. 一种可视化是否比另一种更合适或更有帮助?请解释你的理由。

  1. 纽约市马拉松冠军。 下面的直方图和箱线图显示了1970年至2023年间纽约市马拉松男女(合并)冠军完赛时间的分布。21

    1. 分布的哪些特征在直方图中明显而在箱线图中不明显?哪些特征在箱线图中明显而在直方图中不明显?

    2. 双峰分布的原因可能是什么?请解释。

    3. 根据下面显示的箱线图,比较男性和女性马拉松时间的分布。

    1. 下面显示的时间序列图是查看这些数据的另一种方式。描述在这张图中可见但在其他图中不可见的内容。


  1. 答案可能有所不同。散点图有助于快速发现变量之间的关联,无论这些关联是简单的趋势形式,还是更复杂的关系。↩︎

  2. 考虑这样一种情况:纵轴代表某种“好”的东西,而横轴代表只有在适度时才有益的东西。健康与饮水量就符合这种描述:我们需要一定的水才能生存,但摄入过多就会产生毒性,甚至可能致命。↩︎

  3. \(x_1\) 对应样本中第一笔贷款的利率, \(x_2\) 对应第二笔贷款的利率,而 \(x_i\) 对应数据集中第 \(i^{th}\) 笔贷款的利率。例如,如果 \(i = 4,\) ,那么我们考察的是 \(x_4,\) ,即数据集中的第四个观测值。↩︎

  4. 样本量为 \(n = 50.\)↩︎

  5. 描述右偏数据的其他方式:向右偏斜、向高端偏斜,或向正值一端偏斜。↩︎

  6. 个人贷款的利率。↩︎

  7. 数据集中可能存在两个身高组:儿童(学生)和成人(教师)。也就是说,数据很可能是双峰的。↩︎

  8. 图 5.7 展示了三个看起来截然不同的分布,但它们的均值、方差和标准差都相同。利用众数模态,我们可以区分第一个图(双峰)和后两个图(单峰)。利用偏度,我们可以区分最后一个图(右偏)和前两个图。虽然像直方图这样的图形能讲述更完整的故事,但我们可以利用模态和形状(对称性/偏斜)来刻画分布的基本信息。↩︎

  9. 箱线图由 Mary Eleanor Spear 引入,她认为箱线图是条形图的一种特殊类型,参见第 166 页 Spear(1952)。人们常常错误地将箱线图归功于 John Tukey,他其实是第一个将其称为“箱线图(box-and-whisker plots)”的人。↩︎

  10. 由于 \(Q_1\)\(Q_3\) 涵盖了数据的中间 50%,而中位数将数据从中间分开,因此有 25% 的数据落在 \(Q_1\) 和中位数之间,另有 25% 的数据落在中位数和 \(Q_3.\)↩︎

  11. 这些目测估计值会因人而异,略有不同: \(Q_1 \approx\) 8%, \(Q_3 \approx\) 14%,IQR \(\approx\) 14 - 8 = 6%.↩︎

  12. 均值比中位数受影响更大。标准差比 IQR 受影响更大。↩︎

  13. 如果我们只是想了解一笔典型的个人贷款是什么样的,中位数可能更有用。然而,如果目标是理解可以按比例扩展的事物,例如如果我们提供 1,000 笔贷款时手头可能需要的总金额,那么均值会更有用。↩︎

  14. 答案会有所不同。高收入与大都市区之间存在一定的对应关系,我们可以看到较深的斑点(较高的家庭收入中位数),不过也有若干例外。你可以寻找自己熟悉的大城市,并尝试在地图上把它们识别为深色斑点。↩︎

  15. mammals 本练习中使用的数据可在 openintro R 包中找到。↩︎

  16. cia_factbook 本练习中使用的数据可在 openintro R 包中找到。↩︎

  17. pm25_2022_durham 本练习中使用的数据可在 openintro R 包中找到。↩︎

  18. oscars 本练习中使用的数据可在 openintro R 包中找到。↩︎

  19. county_complete 本练习中使用的数据可在 usdata R 包中找到。↩︎

  20. county_complete 本练习中使用的数据可在 usdata R 包中找到。↩︎

  21. nyc_marathon 本练习中使用的数据可在 openintro R 包中找到。↩︎