Chapter page 9 / 384 Exploring categorical data
English

4  Exploring categorical data

This chapter focuses on exploring categorical 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. Where possible, we present multivariate plots; plots that visualize the relationship between multiple variables. Mastery of the content presented in this chapter will be crucial for understanding the methods and techniques introduced in the rest of the book.

In this chapter we will work with data on loans from Lending Club that you’ve previously seen in Chapter 1. The loan50 dataset from Chapter 1 represents a sample from a larger loan dataset called loans. This larger dataset contains information on 10,000 loans made through Lending Club. We will examine the relationship between homeownership, which for the loans data can take a value of rent, mortgage (owns but has a mortgage), or own, and application_type, which indicates whether the loan application was made with a partner or whether it was an individual application.

The loans_full_schema data can be found in the openintro R package. Based on the data in this dataset we have modified the homeownership and application_type variables. We will refer to this modified dataset as loans.

4.1 Contingency tables and bar plots

Table 4.1 summarizes two variables: application_type and homeownership. Note that loans from Lending Club are typically for small items or for cash, not for homes. The individuals in the dataset are taking out loans for their personal use, and we categorize them based on their homeownership status (which is unrelated to the purpose of the loan). A table that summarizes data for two categorical variables in this way is called a contingency table. Each value in the table represents the number of times a particular combination of variable outcomes occurred.

For example, the value 3496 corresponds to the number of loans in the dataset where the borrower rents their home and the application type was by an individual. Row and column totals are also included. The row totals provide the total counts across each row and the column totals down each column. We can also create a table that shows only the overall percentages or proportions for each combination of categories, or we can create a table for a single variable, such as the one shown in Table 4.2 for the homeownership variable.

Table 4.1: A contingency table for application type and homeownership.
homeownership
application_type rent mortgage own Total
joint 362 950 183 1495
individual 3496 3839 1170 8505
Total 3858 4789 1353 10000
Table 4.2: A table summarizing the frequencies for each value of the homeownership variable – mortgage, own, and rent.
homeownership Count
rent 3858
mortgage 4789
own 1353
Total 10000

A bar plot is a common way to display a single categorical variable. Figure 4.1 (a) displays a bar plot of the homeownership variable. In Figure 4.1 (b) the counts are converted into proportions, showing the proportion of observations that are in each level.

Counts and proportions of values of the homeownership variable. The highest proportion of borrowers have a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(a) Counts of homeownership.
Counts and proportions of values of the homeownership variable. The highest proportion of borrowers have a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(b) Proportions of homeownership.
Figure 4.1: Distribution of homeownership.

4.2 Visualizing two categorical variables

4.2.1 Bar plots with two variables

We can display the distributions of two categorical variables on a bar plot concurrently. Such plots are generally useful for visualizing the relationship between two categorical variables. Figure 4.2 shows three such plots that visualize Figure 4.2 (a) is a stacked bar plot. This plot most clearly displays that loan applicants most commonly live in mortgaged homes. It is difficult to say, based on this plot alone, how different application types vary across the levels of homeownership. Figure 4.2 (b) is a standardized bar plot (also known as filled bar plot). This type of visualization is helpful in understanding the fraction of individual or joint loan applications for borrowers in each level of homeownership. Additionally, since the proportions of joint and individual loans vary across the groups, we can conclude that the two variables are associated for this sample. Finally, Figure 4.2 (c) is a dodged bar plot. This plot most clearly displays that within each level of homeownership, individual applications are more common than joint applications. This plot most clearly displays that joint applications are most common among loans for applicants who live in mortgaged homes, compared to renters and owners.

Three bar plots (stacked, dodged, and standardized) displaying homeownership and application type variables. There are three or four times as many individual applications as joint applications. The highest proportion of borrowers has a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(a) Stacked bar plot
Three bar plots (stacked, dodged, and standardized) displaying homeownership and application type variables. There are three or four times as many individual applications as joint applications. The highest proportion of borrowers has a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(b) Standardized bar plot

 

Three bar plots (stacked, dodged, and standardized) displaying homeownership and application type variables. There are three or four times as many individual applications as joint applications. The highest proportion of borrowers has a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(c) Dodged bar plot

 

Figure 4.2: Three bar plots displaying homeownership and application type variables.

Examine the three bar plots in Figure 4.2. When is the stacked, dodged, or standardized bar plot the most useful?


The stacked bar plot is most useful when it’s reasonable to assign one variable as the explanatory variable (here homeownership) and the other variable as the response (here application_type) since we are effectively grouping by one variable first and then breaking it down by the others.

Dodged bar plots are more agnostic in their display about which variable, if any, represents the explanatory and which the response variable. It is also easy to discern the number of cases in each of the six different group combinations. However, one downside is that it tends to require more horizontal space; the narrowness of Plot B compared to the other two in Figure 4.2 makes the plot feel a bit cramped. Additionally, when two groups are of very different sizes, as we see in the group own relative to either of the other two groups, it is difficult to discern if there is an association between the variables.

The standardized stacked bar plot is helpful if the primary variable in the stacked bar plot is relatively imbalanced, e.g., the category has only a third of the observations in the category, making the simple stacked bar plot less useful for checking for an association. The major downside of the standardized version is that we lose all sense of how many cases each of the bars represents.

4.2.2 Mosaic plots

A mosaic plot is a visualization technique suitable for contingency tables that resembles a standardized stacked bar plot with the benefit that we still see the relative group sizes of the primary variable as well.

To get started in creating our first mosaic plot, we’ll break a square into columns for each category of the variable, with the result shown in Figure 4.3 (a). Each column represents a level of homeownership, and the column widths correspond to the proportion of loans in each of those categories. For instance, there are fewer loans where the borrower is an owner than where the borrower has a mortgage. In general, mosaic plots use box areas to represent the number of cases in each category.

Figure 4.3 (b) displays the relationship between homeownership and application type. Each column is split proportionally to the number of loans from individual and joint borrowers. For example, the second column represents loans where the borrower has a mortgage, and it was divided into individual loans (upper) and joint loans (lower). As another example, the bottom segment of the third column represents loans where the borrower owns their home and applied jointly, while the upper segment of this column represents borrowers who are homeowners and filed individually. We can again use this plot to see that the homeownership and application_type variables are associated, since some columns are divided in different vertical locations than others, which was the same technique used for checking an association in the standardized stacked bar plot.

Two mosaic plots, one for homeownership alone and the other displaying the relationship between homeownership and application type. Again, the majority of borrowers are individuals, as compared with joint applications. The highest proportion of borrowers have a mortgage; the next highest proportion rent their home; and the smallest group owns their home outright.
(a) Homeownership.
Two mosaic plots, one for homeownership alone and the other displaying the relationship between homeownership and application type. Again, the majority of borrowers are individuals, as compared with joint applications. The highest proportion of borrowers have a mortgage; the next highest proportion rent their home; and the smallest group owns their home outright.
(b) Homeownership vs. application type.
Figure 4.3: Two mosaic plots, one for homeownership alone and the other displaying the relationship between homeownership and application type.

In Figure 4.3, we chose to first split by the homeowner status of the borrower. However, we could have instead first split by the application type, as in Figure 4.4. Like with the bar plots, it’s common to use the explanatory variable to represent the first split in a mosaic plot, and then for the response to break up each level of the explanatory variable if these labels are reasonable to attach to the variables under consideration.

Mosaic plot where loans are grouped by homeownership after they have been divided into individual and joint application types. Again, the majority of borrowers are individuals, as compared with joint applications. The highest proportion of borrowers have a mortgage; the next highest proportion rent their home; and the smallest group owns their home outright.
Figure 4.4: Mosaic plot where loans are grouped by homeownership after they have been divided into individual and joint application types.

4.3 Row and column proportions

In the previous sections we inspected visualizations of two categorical variables in bar plots and mosaic plots. However, we have not discussed how the values in the bar and mosaic plots that show proportions are calculated. In this section we will investigate fractional breakdown of one variable in another and we can modify our contingency table to provide such a view. Table 4.3 shows row proportions for Table 4.1, which are computed as the counts divided by their row totals. The value 3496 at the intersection of individual and rent is replaced by \(3496 / 8505 = 0.411,\) i.e., 3496 divided by its row total, 8505. So, what does 0.411 represent? It corresponds to the proportion of individual applicants who rent.

Table 4.3: A contingency table with row proportions for application type and homeownership.
homeownership
application_type rent mortgage own Total
joint 0.242 0.635 0.122 1
individual 0.411 0.451 0.138 1

A contingency table of the column proportions is computed in a similar way, where each is computed as the count divided by the corresponding column total. Table 4.4 shows such a table, and here the value 0.906 indicates that 90.6% of renters applied as individuals for the loan. This rate is higher compared to loans from people with mortgages (80.2%) or who own their home (86.5%). Because these rates vary between the three levels of homeownership (rent, mortgage, own), this provides evidence that application_type and homeownership variables may be associated.

Table 4.4: A contingency table with column proportions for application type and homeownership.
homeownership
application_type rent mortgage own
joint 0.094 0.198 0.135
individual 0.906 0.802 0.865
Total 1.000 1.000 1.000

Row and column proportions can also be thought of as conditional proportions as they tell us about the proportion of observations in a given level of a categorical variable conditional on the level of another categorical variable.

We could also have checked for an association between application_type and homeownership in Table 4.3 using row proportions. When comparing these row proportions, we would look down columns to see if the fraction of loans where the borrower rents, has a mortgage, or owns varied across the application types.

What does 0.451 represent in Table 4.3? What does 0.802 represent in Table 4.4?1

What does 0.122 represent in Table 4.3? What does 0.135 represent in Table 4.4?2

Data scientists use statistics to build email spam filters. By noting specific characteristics of an email, a data scientist may be able to classify some emails as spam or not spam with high accuracy. One such characteristic is the email format, which indicates whether an email has any HTML content, such as bolded text. We’ll focus on email format and spam status using the dataset; these variables are summarized in a contingency table in Table 4.5. Which would be more helpful to someone hoping to classify email as spam or regular email for this table: row or column proportions?


A data scientist would be interested in how the proportion of spam changes within each email format. This corresponds to column proportions: the proportion of spam in plain text emails and the proportion of spam in HTML emails. If we generate the column proportions, we can see that a higher fraction of plain text emails are spam (\(209/1195 = 17.5\%\)) than compared to HTML emails (\(158/2726 = 5.8\%\)). This information on its own is insufficient to classify an email as spam or not spam, as over 80% of plain text emails are not spam. Yet, when we carefully combine this information with many other characteristics, we stand a reasonable chance of being able to classify some emails as spam or not spam with confidence. This example points out that row and column proportions are not equivalent. Before settling on one form for a table, it is important to consider each to ensure that the most useful table is constructed. However, sometimes it simply isn’t clear which, if either, is more useful.

The email data can be found in the openintro R package.

Table 4.5: A contingency table for spam and format.
spam HTML text Total
not spam 2568 986 3554
spam 158 209 367
Total 2726 1195 3921

Look back to Table 4.3 and Table 4.4. Are there any obvious scenarios where one might be more useful than the other?


None that we think are obvious! What is distinct about the email example is that the two loan variables do not have a clear explanatory-response variable relationship that we might hypothesize. Usually it is most useful to “condition” on the explanatory variable. For instance, in the email example, the email format was seen as a possible explanatory variable of whether the message was spam, so we would find it more interesting to compute the relative frequencies (proportions) for each email format.

4.4 Pie charts

A pie chart is shown in Figure 4.5 (a) alongside a bar plot representing the same information in Figure 4.5 (b). Pie charts can be useful for giving a high-level overview to show how a set of cases break down. However, it is also difficult to decipher certain details in a pie chart. For example, it’s not immediately obvious that there are more loans where the borrower has a mortgage than rent when looking at the pie chart, while this detail is very obvious in the bar plot.

A pie chart and bar plot of homeownership. Both plots show that about half of the individuals taking out a loan have a mortgage. A slightly smaller group of individuals rents. The smallest group of borrowers owns their home.
(a) Pie chart

 

A pie chart and bar plot of homeownership. Both plots show that about half of the individuals taking out a loan have a mortgage. A slightly smaller group of individuals rents. The smallest group of borrowers owns their home.
(b) Bar plot
Figure 4.5: A pie chart and bar plot of homeownership.

Pie charts can work well when the goal is to visualize a categorical variable with very few levels, and especially if each level represents a simple fraction (e.g., one-half, one-quarter, etc.). However, they can be quite difficult to read when they are used to visualize a categorical variable with many levels. For example, the pie chart Figure 4.6 (a) and the Figure 4.6 (b) both represent the distribution of loan grades (A through G). In this case, it is far easier to compare the counts of each loan grade using the bar plot than the pie chart.

A pie chart and a bar plot of loan grades. Both plots shows that the most frequent grades are A, B, and C. The bar plot makes it easier to count the number of loans in each grade.
(a) Pie chart

 

A pie chart and a bar plot of loan grades. Both plots shows that the most frequent grades are A, B, and C. The bar plot makes it easier to count the number of loans in each grade.
(b) Bar plot
Figure 4.6: A pie chart and bar plot of loan grades.

4.5 Waffle charts

Another useful technique of visualizing categorical data is a waffle chart. Waffle charts can be used to communicate the proportion of the data that falls into each level of a categorical variable. Just like with pie charts, they work best when the number of levels represented is low. However, unlike pie charts, they can make it easier to compare proportions that represent non-simple fractions. Figure 4.7 (a) is a waffle chart of homeownership and Figure 4.7 (b) is a waffle chart of loan status.

Waffle chart of homeownership, with levels rent, mortgage, and own, and waffle chart of loan status, with levels current, fully paid, in grace period, and late. The waffle charts are broken down into a 10 by 10 grid where each square represents 1 percent of the data. The squares are colored proportionally to the variable distributions.
(a) Homeownership: rent, mortgage, and own

 

Waffle chart of homeownership, with levels rent, mortgage, and own, and waffle chart of loan status, with levels current, fully paid, in grace period, and late. The waffle charts are broken down into a 10 by 10 grid where each square represents 1 percent of the data. The squares are colored proportionally to the variable distributions.
(b) Loan status: fully paid, in grace period, and late
Figure 4.7: Waffle charts of homeownership and loan status.

4.6 Comparing numerical data across groups

Some of the more interesting investigations can be considered by examining numerical data across groups. In this section we will expand on a few methods we have already seen to make plots for numerical data from multiple groups on the same graph as well as introduce a few new methods for comparing numerical data across groups.

We will revisit the county dataset and compare the median household income for counties that gained population from 2010 to 2017 versus counties that had no gain. While we might like to make a causal connection between income and population growth, remember that these are observational data and so such an interpretation would be, at best, half-baked.

We have data on 3142 counties in the United States. We are missing 2017 population data from 3 of them, and of the remaining 3139 counties, in 1541 the population increased from 2010 to 2017 and in the remaining 1598 the population decreased. Table 4.6 shows a sample of four observations from each group.

Table 4.6: The median household income from a random sample of four counties with population gain between 2010 to 2017 and another random sample of four counties with no population gain.
State County Population change (%) Gain / No gain Median household income
Arkansas Izard County 2.13 gain 39135
Georgia Jackson County 10.17 gain 57999
Oregon Hood River County 3.41 gain 57269
Texas Montague County 0.75 gain 46592
Kentucky Ballard County -2.62 no gain 42988
Kentucky Letcher County -5.13 no gain 30293
Texas Jim Hogg County -1.12 no gain 31403
Virginia Richmond County -0.19 no gain 47341

Color can be used to split histograms (see Section 5.3 for an introduction to histograms) for numerical variables by levels of a categorical variable. An example of this is shown in Figure 4.8 (a). The side-by-side box plot is another traditional tool for comparing across groups. An example is shown in Figure 4.8 (b), where there are two box plots (see Section 5.5 for an introduction to box plots), one for each group, placed into one plotting window and drawn on the same scale.

Histograms and side by-side box plots of median household income, where counties are split by whether there was a population gain or not. In both plots, the counties who have had a population gain have a household income distribution with a higher center. Additionally, the histogram (but not the boxp lot) shows that there are more counties who have had a population gain than who have not had a population gain.
(a) Histograms
Histograms and side by-side box plots of median household income, where counties are split by whether there was a population gain or not. In both plots, the counties who have had a population gain have a household income distribution with a higher center. Additionally, the histogram (but not the boxp lot) shows that there are more counties who have had a population gain than who have not had a population gain.
(b) Side by-side box plots
Figure 4.8: Visualizations of median household income of counties by change in population (gain or loss).

Use the plots in Figure 4.8 to compare the incomes for counties across the two groups. What do you notice about the approximate center of each group? What do you notice about the variability between groups? Is the shape relatively consistent between groups? How many prominent modes are there for each group?3

What components of each plot in Figure 4.8 do you find most useful?4

Another useful visualization for comparing numerical data across groups is a ridge plot, which combines density plots (see Section 5.5 for an introduction to density plots) for various groups drawn on the same scale in a single plotting window. Figure 4.9 displays a ridge plot for the distribution of median household income in counties, split by whether there was a population gain or not.

Ridge plot for median household income, where counties are split by whether there was a population gain or not. The figure shows that the counties who have had a population gain have a household income distribution with a higher center.
Figure 4.9: Ridge plot for median household income, where counties are split by whether there was a population gain or not.

What components of the ridge plot in Figure 4.9 do you find most useful compared to those in Figure 4.8?5

One last visualization technique we’ll highlight for comparing numerical data across groups is faceting. In this technique we split (facet) the graphical display of the data across plotting windows based on groups. In Figure 4.10 (a) displays the same information as Figure 4.8 (a), however here the distributions of median household income for counties with and without population gain are faceted across two plotting windows. We preserve the same scale on the x and y axes for easier comparison. An advantage of this approach is that it extends to splitting the data across levels of two categorical variables, which allows for displaying relationships between three variables. In Figure 4.10 (b) we have now split the data into four groups using the pop_change and metro variables:

  • top left represents counties that are not in a metropolitan area with population gain,
  • top right represents counties that are in a metropolitan area with population gain,
  • bottom left represents counties that are not in a metropolitan area without population gain, and finally
  • bottom right represents counties that are in a metropolitan area without population gain.
Distribution of median income in counties, faceted by whether there was a population gain or not.
(a) By population gain.
Distribution of median income in counties, faceted by whether there was a population gain and whether the county is in a metropolitan area. Those counties in metropolitan areas have household income distributions which are higher than those which are not in metropolitan araes.
(b) By both population gain and metropolitan area.
Figure 4.10: Distribution of median income in counties using faceted histograms.

We can continue building upon this visualization to add one more variable, median_edu, which is the median education level in the county. In Figure 4.11, we represent median education level using color, where pink (solid line) represents counties where the median education level is high school diploma, yellow (dashed line) is some college degree, and red (dotted line) is Bachelor’s.

Based on Figure 4.11, what can you say about how median household income in counties vary depending on population gain/no gain, metropolitan area/not, and median degree?6

Distribution of median income in counties using a ridge plot, faceted by whether the county had a population gain or not as well as whether the county is in a metropolitan area and colored by the median education level in the county. Those counties where the median education level is a bachelor's degree have household income distributions that are substantially higher than counties with some college or high school degree only as their education level.
Figure 4.11: Distribution of median income in counties using a ridge plot, faceted by whether the county had a population gain or not as well as whether the county is in a metropolitan area and colored by the median education level in the county.

4.7 Chapter review

4.7.1 Summary

Fluently working with categorical variables is an important skill for data analysts. In this chapter we have introduced different visualizations and numerical summaries applied to categorical variables. The graphical visualizations are even more descriptive when two variables are presented simultaneously. We presented bar plots, mosaic plots, pie charts, and estimations of conditional proportions.

4.7.2 Terms

The terms introduced in this chapter are presented in Table 4.7. 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 4.7: Terms introduced in this chapter.
column proportions faceted plot row totals
column totals filled bar plot side-by-side box plot
conditional proportions mosaic plot stacked bar plot
contingency table ridge plot standardized bar plot
dodged bar plot row proportions

4.8 Exercises

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

  1. Antibiotic use in children. The bar plot and the pie chart below show the distribution of pre-existing medical conditions of children involved in a study on the optimal duration of antibiotic use in treatment of tracheitis, which is an upper respiratory infection.7

    1. What features are apparent in the bar plot but not in the pie chart?

    2. What features are apparent in the pie chart but not in the bar plot?

    3. Which graph would you prefer to use for displaying these categorical data?

  1. Views on immigration. Nine-hundred and ten (910) randomly sampled registered voters from Tampa, FL were asked if they thought workers who have illegally entered the US should be (i) allowed to keep their jobs and apply for US citizenship, (ii) allowed to keep their jobs as temporary guest workers but not allowed to apply for US citizenship, or (iii) lose their jobs and have to leave the country. The results of the survey by political ideology are shown below.8

    Response Conservative Liberal Moderate Total
    Apply for citizenship 57 101 120 278
    Guest worker 121 28 113 262
    Leave the country 179 45 126 350
    Not sure 15 1 4 20
    Total 372 175 363 910
    1. What percent of these Tampa, FL voters identify themselves as conservatives?

    2. What percent of these Tampa, FL voters are in favor of the citizenship option?

    3. What percent of these Tampa, FL voters identify themselves as conservatives and are in favor of the citizenship option?

    4. What percent of these Tampa, FL voters who identify themselves as conservatives are also in favor of the citizenship option? What percent of moderates share this view? What percent of liberals share this view?

    5. Do political ideology and views on immigration appear to be associated? Explain your reasoning.

    6. Conjecture other variables that might explain the potential relationship between these two variables.

  1. Black Lives Matter. A Washington Post-Schar School poll conducted in the United States in June 2020, among a random national sample of 1,006 adults, asked respondents whether they support or oppose protests following George Floyd’s killing that have taken place in cities across the US. The survey also collected information on the age of the respondents. (Washington Post 2020) The results are summarized in the stacked bar plot below.

    1. Based on the stacked bar plot, do views on the protests and age appear to be associated? Explain your reasoning.

    2. Conjecture other possible variables that might explain the potential association between these two variables.

  1. Raise taxes. A random sample of registered voters nationally were asked whether they think it’s better to raise taxes on the rich or raise taxes on the poor. The survey also collected information on the political party affiliation of the respondents. (Polling 2015)

    1. Based on the stacked bar plot shown above, do views on raising taxes and political affiliation appear to be associated? Explain your reasoning.

    2. Conjecture other possible variables that might explain the potential association between these two variables.

  1. Heart transplant data display. The Stanford University Heart Transplant Study was conducted to determine whether an experimental heart transplant program increased lifespan. Each patient entering the program was officially designated a heart transplant candidate, meaning that they were gravely ill and might benefit from a new heart. Patients were randomly assigned into treatment and control groups. Patients in the treatment group received a transplant, and those in the control group did not. The visualizations below display two different versions of the study results.9 (Turnbull et al. 1974)

    1. Provide one aspect of the two group comparison that is easier to see from the stacked bar plot (left)?

    2. Provide one aspect of the two group comparison that is easeir to see from the standardized bar plot (right)?

    3. For the Heart Transplant Study which of those aspects would be more important to display? That is, which bar plot would be better as a data visualization?

  1. Shipping holiday gifts data display. A local news survey asked 500 randomly sampled Los Angeles residents which shipping carrier they prefer to use for shipping holiday gifts. The bar plots below show the distribution of responses by age group as well as distribution of responses by shipping method.

    1. Which graph (top or bottom) would you use to understand the shipping choices of people of different ages? Explain.

    2. Which graph (top or bottom) would you use to understand the age distribution across different types of shipping choices? Explain.

    3. A new shipping company would like to market to people over the age of 55. Who will be their biggest competitor? Explain.

    4. FedEx would like to reach out to grow their market share so as to balance the age demographics of FedEx users. To what age group should FedEx market?

  1. Meat consumption and life expectancy. In data collected for You et al. (2022), total meat intake is associated with life expectancy (at birth) in 175 countries. Meat intake is measured in kg per capita per year (averaged over 2011 to 2013). The two ridge plots show an association between income and meat consumption (higher income countries tend to eat more meat) and an association between income and life expectancy (higher income countries have higher life expectancy).

    1. Do the graphs above demonstrate that meat consumption and life expectancy are associated? That is, can you tell if countries with low meat consumption have low life expectancy? Explain.

    2. Let’s assume that you had a plot comparing meat consumption and life expectancy, and they do seem associated. Your friend says that the plot shows that high meat consumption leads to a longer life. You correctly say, no, we can’t tell if there is a causal realtionship because the relationship is confounded by income level. Explain what you mean.

    3. How can you investigate the relationship between meat consumption and life expectancy in the presence of confounding variables (like income)?

  1. Florence Nightingale. Florence Nightingale was a nurse in the Crimean War and an early statistician. In her notes, she opined, “In comparing the deaths of one hospital with those of another, any statistics are justly considered absolutely valueless which do not give the ages, the sexes, and the diseases of all the cases.” (Nightingale 1859)

    1. Nightingale describes three confounding variables to consider when comparing death rates across hospitals. What are they? Describe what makes each variable potentially confounding.

    2. Provide two additional potential confounding variables for this situation. Check to make sure that the variables are associated with both the explanatory variable (hospital) and the response variable (death).

    3. Why does Nightingale say that the statistics are “valueless” if given without being broken down by age, sex, and disease? Explain.

  1. On-time arrivals. Consider all of the flights out of New York City in 2013 that flew into Puerto Rico (BQN), Los Angeles (LAX), or San Francisco (SFO) on the following two airlines: JetBlue (B6) or United Airlines (UA). Below are the tabulated counts for the number of flights delayed and on time for each airline into each city.10

    dest carrier status count
    BQN B6 delayed 271
    BQN B6 on time 322
    BQN UA delayed 144
    BQN UA on time 151
    LAX B6 delayed 670
    LAX B6 on time 999
    LAX UA delayed 2368
    LAX UA on time 3402
    SFO B6 delayed 405
    SFO B6 on time 615
    SFO UA delayed 2694
    SFO UA on time 4034
    1. What percent of all JetBlue flights were delayed? What percent of all United Airlines flights were delayed? (Note, the overall delay proportions are typically what would be reported and associated with an airline.)

    2. For each of the three airports, find the percent of delayed flights for each of JetBlue and United (you should have 6 numbers).

    3. United has a higher proportion of delayed flights for each of the three cities, yet JetBlue has a higher proportion of delayed flights overall. Explain, using the data counts provided, how the seeming paradox could happen.11

  2. US House of Representatives. The US House of Representatives is dominated by two political parties: Democrats and Republicans. Democrats are thought to be the more liberal party and Republicans are considered to be the more conservative party. However, within each party there is an internal spectrum of liberal to conservative. For example, conservative Democrats and liberal Republicans would be labeled moderate. Consider an election where the only change in membership is that the most conservative Democrats are replaced by a set of liberal Republicans who are more liberal than the incumbent Republicans but more conservative than the Democrats they replaced.

    1. After the election, is the Democratic wing of the House more conservative or more liberal? Explain.

    2. After the election, is the Republican wing of the House more conservative or more liberal? Explain.

    3. After the election, is the overall House membership more conservative or more liberal? Explain.

    4. In what settings would you report the outcome of the change in House membership to be more conservative? And in what settings would you report the outcome of the change in House membership to be more liberal?12


  1. 0.451 represents the proportion of individual applicants who have a mortgage. 0.802 represents the fraction of applicants with mortgages who applied as individuals.↩︎

  2. 0.122 represents the fraction of joint borrowers who own their home. 0.135 represents the home-owning borrowers who had a joint application for the loan.↩︎

  3. Answers may vary a little. The counties with population gains tend to have higher income (median of about $45,000) versus counties without a gain (median of about $40,000). The variability is also slightly larger for the population gain group. This is evident in the IQR, which is about 50% bigger in the gain group. Both distributions show slight to moderate right skew and are unimodal. The box plots indicate there are many observations far above the median in each group, though we should anticipate that many observations will fall beyond the whiskers when examining any dataset that contain more than a few hundred data points.↩︎

  4. Answers will vary. The side-by-side box plots are especially useful for comparing centers and spreads, while the hollow histograms are more useful for seeing distribution shape, skew, modes, and potential anomalies.↩︎

  5. The ridge plot give us a better sense of the shape, and especially modality, of the data.↩︎

  6. Regardless of the location (metropolitan or not) or change in population, it seems like there is an increase in median household income from individuals with only a HS diploma, to individuals with some college, to individuals with a Bachelor’s degree.↩︎

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

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

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

  10. The flights data used in this exercise can be found in the nycflights13 R package.↩︎

  11. The conundrum is known as Simpson’s Paradox and is explored in Chapter 3.↩︎

  12. The conundrum is known as Simpson’s Paradox and is explored in Chapter 3.↩︎

中文

4  探索分类数据

本章重点通过汇总统计量和可视化来探索 分类 数据。本章所呈现的汇总结果与图形均使用统计软件创建;不过,由于这可能是你初次接触这些概念,我们将在本章中花些时间详细介绍如何创建它们。在可能的情况下,我们会呈现多变量图,即可视化多个变量之间关系的图形。掌握本章所呈现的内容,对于理解本书其余部分所介绍的方法和技术至关重要。

在本章中,我们将使用来自 Lending Club 的贷款数据,这些数据此前已见于 第 1 章。而 loan50 数据集来自 第 1 章 ,它代表了来自一个更大的贷款数据集的样本,该数据集名为 loans。这个更大的数据集包含通过 Lending Club 发放的 10,000 笔贷款的信息。我们将考察以下变量之间的关系: homeownership,对于 loans 数据,其取值可以为 rent, mortgage (拥有住房但尚有抵押贷款),或 ownapplication_type,该变量表示贷款申请是与人共同申请,还是个人单独申请。

loans_full_schema 数据可以在 openintro R 包。基于该数据集中的数据,我们修改了 homeownershipapplication_type 变量。我们将把这个修改后的数据集称为 loans.

4.1 列联表与条形图

表 4.1 总结了两个变量: application_typehomeownership。请注意,Lending Club 的贷款通常用于购买小件物品或获取现金,而不是用于住房。数据集中的个人是出于个人用途而申请贷款,我们根据他们的 homeownership 状况(这与贷款的目的无关)。以这种方式汇总两个分类变量数据的表称为 列联表。表中的每个值表示变量的某种特定结果组合出现的次数。

例如,数值 3496 对应的是数据集中借款人租房居住且申请类型为个人申请的贷款笔数。表中还包含了行总计和列总计。 行总计 给出了每一行计数的总和,而 列总计 沿每一列向下。我们也可以创建一个仅显示每个类别组合的总体百分比或比例的表格,或者我们也可以为单个变量创建一个表格,例如 表 4.2 中针对 homeownership 变量所示的那个。

表 4.1:申请类型与住房所有权的列联表。
homeownership
application_type 租金 抵押贷款 own 总计
joint 362 950 183 1495
单个 3496 3839 1170 8505
总计 3858 4789 1353 10000
表 4.2:汇总 homeownership 变量各取值频数的表格——mortgage、own 和 rent。
homeownership 频数
租金 3858
抵押贷款 4789
own 1353
总计 10000

条形图是展示单个分类变量的一种常用方式。 图 4.1 (a) 展示了一个 条形图 ,针对 homeownership 变量。在 图 4.1 (b) 中,计数被转换为比例,显示了处于每个水平中的观测值所占的比例。

Counts and proportions of values of the homeownership variable. The highest proportion of borrowers have a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(a) 住房拥有情况的计数。
Counts and proportions of values of the homeownership variable. The highest proportion of borrowers have a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(b) 住房拥有情况的比例。
图 4.1:住房拥有情况的分布。

4.2 两个分类变量的可视化

4.2.1 含两个变量的条形图

我们可以在一张条形图上同时展示两个分类变量的分布。这类图通常有助于可视化两个分类变量之间的关系。 图 4.2 展示了三幅这样的图,可视化了 图 4.2 (a)堆叠条形图。这张图最清楚地显示出贷款申请人最常居住在有抵押贷款的住房中。但仅凭这张图,很难说明不同类型的申请在住房拥有情况的各个水平之间如何变化。 图 4.2 (b)标准化条形图 (也称为 填充条形图)。这种类型的可视化有助于理解在每个 homeownership的水平上,借款人个人或联合申请贷款所占的比例。此外,由于联合贷款和个人贷款的比例在各组之间有所不同,我们可以得出结论:对于该样本,这两个变量是相关联的。最后, 图 4.2 (c)并列条形图。该图最清楚地显示,在 homeownership 的每个水平上,个人申请比联合申请更为常见。该图最清楚地显示,与租房者和房主相比,联合申请在居住于抵押住房的申请人的贷款中最为常见。

Three bar plots (stacked, dodged, and standardized) displaying homeownership and application type variables. There are three or four times as many individual applications as joint applications. The highest proportion of borrowers has a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(a) 堆叠条形图
Three bar plots (stacked, dodged, and standardized) displaying homeownership and application type variables. There are three or four times as many individual applications as joint applications. The highest proportion of borrowers has a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(b) 标准化条形图

 

Three bar plots (stacked, dodged, and standardized) displaying homeownership and application type variables. There are three or four times as many individual applications as joint applications. The highest proportion of borrowers has a home mortgage. The next highest group rents. The smallest group of people own their home outright.
(c) 并列条形图

 

图 4.2:展示 homeownership 和申请类型变量的三个条形图。

查看 图 4.2中的三个条形图。什么时候堆叠条形图、并列条形图或标准化条形图最有用?


当可以合理地将其中一个变量指定为解释变量时,堆叠条形图最为有用(此处为 homeownership),另一个变量作为响应变量(此处为 application_type),因为我们实际上是先按一个变量分组,然后再按其他变量进行细分。

并排条形图在展示上对哪个变量(如果有的话)代表解释变量、哪个代表响应变量更加不可知。同时也很容易看出六种不同组合中各自案例的数量。然而,一个缺点是它往往需要更多的水平空间;在 图 4.2 中,图 B 与其他两个图相比显得较窄,使图形看起来有些局促。此外,当两个组的大小差异很大时,正如我们在组 own 中相对于其他两个组所看到的那样,很难判断变量之间是否存在关联。

如果堆叠条形图中的主要变量相对不平衡,标准化堆叠条形图会很有帮助,例如,某类别只有另一类别三分之一的观测值,这会使简单的堆叠条形图在检验关联性时不太有用。标准化版本的主要缺点是我们失去了对每个条形代表多少案例的感知。

4.2.2 马赛克图

一个 马赛克图 是一种适用于列联表的可视化技术,它类似于标准化堆叠条形图,但优点是我们仍然可以看到主要变量的相对组大小。

为了开始创建我们的第一个马赛克图,我们将一个正方形按变量的每个类别划分为若干列,结果如 图 4.3 (a)所示。每一列代表 homeownership的一个水平,列宽对应于各类别中贷款所占的比例。例如,借款人为业主的贷款少于借款人有抵押贷款的贷款。一般来说,马赛克图使用方块的 面积 来表示每个类别中的案例数量。

图 4.3 (b) 展示了房屋所有权与申请类型之间的关系。每一列按个人借款和共同借款的贷款数量成比例地拆分。例如,第二列代表借款人有抵押贷款的贷款,它被分为个人贷款(上部)和共同贷款(下部)。再举一个例子,第三列的底部部分代表借款人拥有自己的住房并共同申请的贷款,而该列的上部部分代表拥有住房并单独申请的借款人。我们同样可以使用此图看出 homeownershipapplication_type 变量之间存在关联,因为有些列在不同的垂直位置被分割,这与在标准化堆叠条形图中检验关联所使用的技术相同。

Two mosaic plots, one for homeownership alone and the other displaying the relationship between homeownership and application type. Again, the majority of borrowers are individuals, as compared with joint applications. The highest proportion of borrowers have a mortgage; the next highest proportion rent their home; and the smallest group owns their home outright.
(a) 房屋所有权。
Two mosaic plots, one for homeownership alone and the other displaying the relationship between homeownership and application type. Again, the majority of borrowers are individuals, as compared with joint applications. The highest proportion of borrowers have a mortgage; the next highest proportion rent their home; and the smallest group owns their home outright.
(b) 房屋所有权与申请类型。
图 4.3:两个马赛克图,一个仅针对房屋所有权,另一个展示房屋所有权与申请类型之间的关系。

图 4.3,我们选择首先按借款人的房屋所有权进行分割。然而,我们也可以像 图 4.4中那样,首先按申请类型进行分割。与条形图一样,通常用解释变量表示马赛克图中的第一次分割,然后如果这些标签合理地适用于所考虑的变量,则用响应变量来细分解释变量的每个水平。

Mosaic plot where loans are grouped by homeownership after they have been divided into individual and joint application types. Again, the majority of borrowers are individuals, as compared with joint applications. The highest proportion of borrowers have a mortgage; the next highest proportion rent their home; and the smallest group owns their home outright.
图 4.4:马赛克图,其中贷款在先被分为个人申请和联合申请类型之后,再按房屋所有权分组。

4.3 行比例与列比例

在前面的章节中,我们在条形图和马赛克图中考察了两个分类变量的可视化。然而,我们尚未讨论条形图和马赛克图中显示比例的数值是如何计算的。在本节中,我们将研究一个变量在另一个变量中的比例分布,并且可以修改列联表以提供这样的视图。 表 4.3 展示了 行比例 ,针对 表 4.1,其计算方式为计数除以其行总计。个人申请与租房交叉处的数值 3496 被替换为 \(3496 / 8505 = 0.411,\) ,即 3496 除以其行总计 8505。那么,0.411 代表什么?它对应于租房的个人申请者的比例。

表 4.3:申请类型与房屋所有权的行比例列联表。
homeownership
application_type 租金 抵押贷款 own 总计
joint 0.242 0.635 0.122 1
单个 0.411 0.451 0.138 1

一个包含 列比例 的计算方式类似,其中每个值都是用计数除以相应的列总和得到的。 表 4.4 展示了这样一张表,其中数值 0.906 表示 90.6% 的租房者以个人身份申请了贷款。这一比例高于有抵押贷款的人群(80.2%)或拥有自己住房的人群(86.5%)的贷款比例。由于这些比例在 homeownership (rent, mortgage, own的三个水平之间存在差异,这提供了证据表明 application_typehomeownership 变量之间可能存在关联。

表 4.4:申请类型与住房所有权按列比例列出的列联表。
homeownership
application_type 租金 抵押贷款 own
joint 0.094 0.198 0.135
单个 0.906 0.802 0.865
总计 1.000 1.000 1.000

行比例和列比例也可以被视为 条件比例 ,因为它们告诉我们在一个分类变量的给定水平上,以另一个分类变量的水平为条件时观测值所占的比例。

我们也可以使用行比例来检验 application_typehomeownership表 4.3 之间是否存在关联。在比较这些行比例时,我们会逐列向下查看,观察借款人租房、有抵押贷款或拥有住房的贷款比例是否因申请类型而异。

0.451 在 表 4.3中代表什么?0.802 在 表 4.4?1

0.122 在 表 4.3中代表什么?0.135 在 表 4.4?2

数据科学家使用统计学来构建垃圾邮件过滤器。通过注意电子邮件的特定特征,数据科学家可能能够高精度地将某些电子邮件分类为垃圾邮件或非垃圾邮件。其中一个特征是电子邮件格式,它表明电子邮件是否包含任何 HTML 内容,例如加粗文本。我们将使用该数据集关注电子邮件格式和垃圾邮件状态;这些变量汇总在 表 4.5. Which would be more helpful...


A data scientist would be interested... spam (\(209/1195 = 17.5\%\)) than compared to HTML emails (\(158/2726 = 5.8\%\)). This information...

email 数据可以在 openintro R 包中找到。

Table 4.5...
spam HTML text 总计
not spam 2568 986 3554
spam 158 209 367
总计 2726 1195 3921

Look back to 表 4.3表 4.4. Are there any obvious scenarios...


None that we think...

4.4 饼图

一个 pie chart is shown in 图 4.5 (a) 以及一个表示相同信息的条形图,见 图 4.5 (b)。饼图可用于提供高层次概览,展示一组案例的构成情况。然而,饼图中的某些细节也难以辨认。例如,仅看饼图时,并不能立刻看出借款人拥有抵押贷款的贷款数量多于租房的贷款数量,而这个细节在条形图中非常明显。

A pie chart and bar plot of homeownership. Both plots show that about half of the individuals taking out a loan have a mortgage. A slightly smaller group of individuals rents. The smallest group of borrowers owns their home.
(a) 饼图

 

A pie chart and bar plot of homeownership. Both plots show that about half of the individuals taking out a loan have a mortgage. A slightly smaller group of individuals rents. The smallest group of borrowers owns their home.
(b) 条形图
图 4.5:住房拥有情况的饼图和条形图。

当目标是可视化水平数很少的分类变量时,饼图可以表现良好,尤其是当每个水平代表一个简单分数(例如二分之一、四分之一等)时。然而,当用饼图来可视化具有较多水平的分类变量时,它们可能相当难以解读。例如,饼图 图 4.6 (a)图 4.6 (b) 都表示贷款等级(A 到 G)的分布。在这种情况下,使用条形图来比较各贷款等级的数量要比使用饼图容易得多。

A pie chart and a bar plot of loan grades. Both plots shows that the most frequent grades are A, B, and C. The bar plot makes it easier to count the number of loans in each grade.
(a) 饼图

 

A pie chart and a bar plot of loan grades. Both plots shows that the most frequent grades are A, B, and C. The bar plot makes it easier to count the number of loans in each grade.
(b) 条形图
图 4.6:贷款等级的饼图和条形图。

4.5 华夫图

另一种可视化分类数据的有用技术是 华夫图。华夫图可用于展示数据中落入分类变量各个水平的比例。与饼图一样,当所表示的水平数量较少时,它们的效果最好。然而,与饼图不同的是,华夫图可以更容易地比较那些代表非简单分数的比例。 图 4.7 (a) 是关于住房所有权的华夫图,而 图 4.7 (b) 是关于贷款状态的华夫图。

Waffle chart of homeownership, with levels rent, mortgage, and own, and waffle chart of loan status, with levels current, fully paid, in grace period, and late. The waffle charts are broken down into a 10 by 10 grid where each square represents 1 percent of the data. The squares are colored proportionally to the variable distributions.
(a) 住房所有权:租房、按揭贷款和自有

 

Waffle chart of homeownership, with levels rent, mortgage, and own, and waffle chart of loan status, with levels current, fully paid, in grace period, and late. The waffle charts are broken down into a 10 by 10 grid where each square represents 1 percent of the data. The squares are colored proportionally to the variable distributions.
(b) 贷款状态:已还清、处于宽限期和逾期
图 4.7:住房所有权与贷款状态的华夫图。

4.6 跨组比较数值数据

通过考察跨组的数值数据,可以进行一些更有趣的研究。在本节中,我们将扩展前面已经介绍的几种方法,以便在同一张图上绘制来自多个组的数值数据,并介绍几种比较跨组数值数据的新方法。

我们将重新考察 county 数据集,并比较2010年至2017年人口有所增长的县与人口没有增长的县的家庭收入中位数。虽然我们可能希望在收入与人口增长之间建立因果联系,但请记住,这些是观察性数据,因此这种解释充其量是不成熟的。

我们拥有美国3142个县的数据。其中3个县缺少2017年人口数据,在其余的3139个县中,有1541个县的人口从2010年到2017年有所增加,其余1598个县的人口则有所减少。 表 4.6 展示了来自每一组的四个观测值的样本。

表 4.6:从2010年至2017年间人口增长的县中随机抽取的四个县,以及从人口没有增长的县中随机抽取的另外四个县的家庭收入中位数。
国营 人口变化 (%) 有增长 / 无增长 家庭收入中位数
阿肯色州 伊泽德县 2.13 增长 39135
佐治亚州 杰克逊县 10.17 增长 57999
俄勒冈州 胡德河县 3.41 增长 57269
得克萨斯州 蒙塔古县 0.75 增长 46592
肯塔基州 巴拉德县 -2.62 无增益 42988
肯塔基州 莱彻县 -5.13 无增益 30293
得克萨斯州 吉姆·霍格县 -1.12 无增益 31403
弗吉尼亚州 里士满县 -0.19 无增益 47341

颜色可用于拆分直方图(参见 第 5.3 节 中对直方图的介绍),以按分类变量的水平展示数值变量。一个示例如 图 4.8 (a)。而 并排箱线图 是另一种用于跨组比较的传统工具。一个示例如 图 4.8 (b),其中有两个箱线图(参见 第5.5节 对箱线图的介绍),每组一个,放在同一个绘图窗口中并使用相同的比例尺绘制。

Histograms and side by-side box plots of median household income, where counties are split by whether there was a population gain or not. In both plots, the counties who have had a population gain have a household income distribution with a higher center. Additionally, the histogram (but not the boxp lot) shows that there are more counties who have had a population gain than who have not had a population gain.
(a) 直方图
Histograms and side by-side box plots of median household income, where counties are split by whether there was a population gain or not. In both plots, the counties who have had a population gain have a household income distribution with a higher center. Additionally, the histogram (but not the boxp lot) shows that there are more counties who have had a population gain than who have not had a population gain.
(b) 并排箱线图
图 4.8:按人口变化(增加或减少)对各县家庭收入中位数的可视化。

使用 图 4.8 中的图比较两组中各县的收入。关于每组的近似中心你注意到什么?关于组间的变异性你注意到什么?两组的形状是否相对一致?每组有多少个 明显 的众数?3

你认为 图 4.8 中每幅图的哪些组成部分最有用?4

另一种用于比较各组数值数据的有用可视化方法是 山脊图,它将密度图(参见 第5.5节 介绍了密度图),将各组的图形绘制在同一标度下的单个绘图窗口中。 图 4.9 展示了各县家庭收入中位数分布的山脊图,并按人口是否增长进行了划分。

Ridge plot for median household income, where counties are split by whether there was a population gain or not. The figure shows that the counties who have had a population gain have a household income distribution with a higher center.
图4.9:家庭收入中位数的山脊图,各县按人口是否增长进行划分。

图 4.9 中的图形相比,你认为 图 4.8?5

我们要重点介绍的另一种跨组比较数值型数据的可视化技术是 分面。在这种技术中,我们根据分组将数据的图形显示拆分(分面)到多个绘图窗口中。在 图 4.10 (a) 中,展示的信息与 图 4.8 (a)相同,但这里将人口增长与人口未增长的县的家庭收入中位数分布分面到两个绘图窗口中。我们保持x轴和y轴使用相同的标度,以便于比较。这种方法的一个优点是它可以扩展到按两个分类变量的水平拆分数据,从而能够展示三个变量之间的关系。在 图 4.10 (b) 中,我们使用 pop_changemetro 变量将数据分成了四组:

  • 左上角代表人口增长的县, 位于一个 metro都市区且人口增长的地区,
  • 右上角表示位于人口增长的都市区内的县,
  • 左下角表示 位于没有人口增长的都市区的县,最后
  • 右下角表示位于没有人口增长的都市区的县。
Distribution of median income in counties, faceted by whether there was a population gain or not.
(a) 按人口增长。
Distribution of median income in counties, faceted by whether there was a population gain and whether the county is in a metropolitan area. Those counties in metropolitan areas have household income distributions which are higher than those which are not in metropolitan araes.
(b) 按人口增长和都市区。
图 4.10:使用分面直方图展示各县收入中位数的分布。

我们可以继续扩展这个可视化,添加另一个变量 median_edu,即该县的教育水平中位数。在 图 4.11中,我们用颜色表示教育水平中位数,其中粉色(实线)代表教育水平中位数为高中文凭的县,黄色(虚线)代表部分大学学历,红色(点线)代表学士学位。

根据 图 4.11,你能就各县的家庭收入中位数如何随人口增长与否、是否位于都市区以及教育水平中位数而变化得出什么结论?6

Distribution of median income in counties using a ridge plot, faceted by whether the county had a population gain or not as well as whether the county is in a metropolitan area and colored by the median education level in the county. Those counties where the median education level is a bachelor's degree have household income distributions that are substantially higher than counties with some college or high school degree only as their education level.
图 4.11:使用山脊图展示各县收入中位数的分布,按该县是否有人口增长以及是否位于都市区进行分面,并按该县的教育水平中位数着色。

4.7 本章复习

4.7.1 小结

熟练处理分类变量是数据分析师的一项重要技能。在本章中,我们介绍了应用于分类变量的不同可视化方法和数值汇总。当同时呈现两个变量时,图形可视化更具描述性。我们介绍了条形图、马赛克图、饼图以及条件比例的估计。

4.7.2 术语

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

表4.7:本章介绍的术语。
列比例 分面图 行总计
列总计 填充条形图 并排箱线图
条件比例 马赛克图 堆叠条形图
列联表 山脊图 标准化条形图
并列条形图 行比例

4.8 练习

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

  1. 儿童抗生素的使用。 下面的条形图和饼图显示了一项关于治疗气管炎(一种上呼吸道感染)抗生素使用最佳时长的研究中,患病儿童的既往疾病分布情况。7

    1. 条形图中哪些特征在饼图中不明显?

    2. 饼图中哪些特征在条形图中不明显?

    3. 你更倾向于使用哪种图形来展示这些分类数据?

  1. 对移民的看法。 从佛罗里达州坦帕市随机抽取的910名登记选民被问及,他们认为非法进入美国的工作者应该:(i) 允许保留工作并申请美国公民身份,(ii) 允许作为临时客籍工人保留工作但不允许申请美国公民身份,还是 (iii) 失去工作并必须离开美国。按政治意识形态划分的调查结果如下所示。8

    回答 保守派 自由派 温和派 总计
    申请公民身份 57 101 120 278
    客籍工人 121 28 113 262
    离开美国 179 45 126 350
    不确定 15 1 4 20
    总计 372 175 363 910
    1. 这些佛罗里达州坦帕市的选民中,自认为是保守派的比例是多少?

    2. 这些佛罗里达州坦帕市的选民中,支持公民身份选项的比例是多少?

    3. 这些佛罗里达州坦帕市的选民中,自认为是保守派且支持公民身份选项的比例是多少?

    4. 这些佛罗里达州坦帕市的选民中,自认为是保守派的人里同时支持公民身份选项的比例是多少?温和派中持这一观点的比例是多少?自由派中持这一观点的比例是多少?

    5. 政治意识形态与对移民问题的看法之间似乎存在关联吗?请解释你的理由。

    6. 推测可能解释这两个变量之间潜在关系的其他变量。

  1. 黑人的命也是命。 2020年6月,《华盛顿邮报》-沙尔学校在美国进行的一项民意调查,在全国随机抽取了1,006名成年人,询问受访者是否支持或反对乔治·弗洛伊德遇害后在美国各城市发生的抗议活动。该调查还收集了受访者的年龄信息。 (华盛顿邮报 2020) 结果汇总在下方的堆叠条形图中。

    1. 根据堆叠条形图,对抗议的看法与年龄之间是否看起来存在关联?请解释你的理由。

    2. 推测其他可能的变量,这些变量或许能解释这两个变量之间潜在的关联。

  1. 提高税收。 一项针对全国登记选民的随机样本调查询问他们认为提高富人的税收还是提高穷人的税收更好。该调查还收集了受访者的政党归属信息。 (2015年民调)

    1. 根据上面显示的堆叠条形图,对提高税收的看法与政治派别之间是否看起来存在关联?请解释你的理由。

    2. 推测其他可能的变量,这些变量或许能解释这两个变量之间潜在的关联。

  1. 心脏移植数据展示。 斯坦福大学心脏移植研究旨在确定实验性心脏移植项目是否能延长寿命。每位进入该项目的患者都被正式指定为心脏移植候选人,这意味着他们病情严重,可能会从新的心脏中受益。患者被随机分配到治疗组与对照组。治疗组的患者接受了移植,而对照组的患者则没有。下面的可视化展示了该研究结果的两个不同版本。9 (Turnbull 等,1974)

    1. 指出从堆叠条形图(左)中更容易看出的两组比较的一个方面?

    2. 指出从标准化条形图(右)中更容易看出的两组比较的一个方面?

    3. 对于心脏移植研究,展示哪些方面更为重要?也就是说,哪种条形图作为数据可视化更好?

  1. 邮寄节日礼物的数据展示。 一项当地新闻调查询问了500名随机抽样的洛杉矶居民,他们在邮寄节日礼物时更喜欢使用哪家快递公司。下面的条形图按年龄组以及按邮寄方式展示了回答的分布。

    1. 你会使用哪张图(上或下)来了解不同年龄人群的邮寄选择?请解释。

    2. 你会使用哪张图(上方的还是下方的)来了解不同运输方式选择中的年龄分布?请解释。

    3. 一家新的运输公司想向55岁以上的人群进行营销。他们最大的竞争对手会是谁?请解释。

    4. FedEx希望拓展市场以平衡FedEx用户的年龄人口结构。FedEx应该向哪个年龄段的人群进行营销?

  1. 肉类消费与预期寿命。 在为 You et al. (2022)收集的数据中,总肉类摄入量与175个国家的预期寿命(出生时)相关。肉类摄入量以每人每年公斤数衡量(2011年至2013年的平均值)。两张脊线图显示了收入与肉类消费之间的关联(收入较高的国家往往吃更多肉)以及收入与预期寿命之间的关联(收入较高的国家预期寿命较高)。

    1. 上面的图表是否证明了肉类消费与预期寿命相关?也就是说,你能判断肉类消费低的国家预期寿命是否也低吗?请解释。

    2. 假设你有一张比较肉类消费与预期寿命的图,而且它们 确实 看起来相关。你的朋友说这张图表明高肉类消费会带来更长的寿命。你正确地指出:不,我们无法判断是否存在因果关系,因为这种关系被收入水平混淆了。请解释你的意思。

    3. 在存在混淆变量(如收入)的情况下,你如何研究肉类消费与预期寿命之间的关系?

  1. 弗洛伦斯·南丁格尔。 弗洛伦斯·南丁格尔是克里米亚战争中的一名护士,也是一位早期的统计学家。她在笔记中写道:“在比较一家医院与另一家医院的死亡情况时,任何不给出所有病例的年龄、性别和疾病的统计数据都被公正地认为是完全没有价值的。” (Nightingale 1859)

    1. 南丁格尔描述了在比较各医院死亡率时需要考虑的三个混淆变量。它们是什么?请描述为什么每个变量都可能成为混淆变量。

    2. 为这种情况再提供两个潜在的混杂变量。请检查确保这些变量既与解释变量(医院)相关,又与响应变量(死亡)相关。

    3. 为什么南丁格尔说,如果不按年龄、性别和疾病进行细分,这些统计数据就是“毫无价值的”?请解释。

  1. 准点到达。 考虑2013年从纽约市出发、飞往波多黎各(BQN)、洛杉矶(LAX)或旧金山(SFO)的以下两家航空公司的所有航班:捷蓝航空(B6)或联合航空(UA)。以下是各航空公司 delayedon time 飞往各城市的航班数量的表格。10

    dest carrier status count
    BQN B6 延误 271
    BQN B6 准时 322
    BQN UA 延误 144
    BQN UA 准时 151
    LAX B6 延误 670
    LAX B6 准时 999
    LAX UA 延误 2368
    LAX UA 准时 3402
    SFO B6 延误 405
    SFO B6 准时 615
    SFO UA 延误 2694
    SFO UA 准时 4034
    1. 捷蓝航空(JetBlue)所有航班中延误的百分比是多少?联合航空(United Airlines)所有航班中延误的百分比是多少?(注,整体延误比例通常是会被报告并与航空公司关联的数据。)

    2. 对于这三个机场中的每一个,分别计算捷蓝航空和联合航空的延误航班百分比(你应该得到6个数字)。

    3. 在这三个城市中,联合航空的延误航班比例都更高,但捷蓝航空的整体延误航班比例却更高。请使用所提供的数据计数解释这一看似矛盾的现象是如何发生的。11

  2. 美国众议院。 美国众议院由两大政党主导:民主党和共和党。民主党被认为更偏自由派,共和党被认为更偏保守派。然而,每个政党内部都存在从自由派到保守派的内部光谱。例如,保守派民主党人和自由派共和党人会被贴上温和派的标签。设想一场选举,成员的唯一变化是:最保守的民主党人被一批自由派共和党人取代,这批人比现任共和党人更自由,但比他们所取代的民主党人更保守。

    1. 选举之后,众议院的民主党一翼是更保守了还是更自由了?请解释。

    2. 选举之后,众议院的共和党一翼是更保守了还是更自由了?请解释。

    3. 选举之后,众议院的整体成员构成是更保守了还是更自由了?请解释。

    4. 在什么情况下你会报告众议院成员变化的结局更为保守?又在什么情况下你会报告这一变化的结局更为自由?12


  1. 0.451表示以个人身份申请且有抵押贷款的申请人比例。0.802表示有抵押贷款的申请人中以个人身份申请的比例。↩︎

  2. 0.122表示共同借款人拥有住房的比例。0.135表示拥有住房的借款人中曾以共同申请方式申请贷款的比例。↩︎

  3. 答案可能略有不同。人口增长的县往往收入更高(中位数约为45,000美元),而人口没有增长的县(中位数约为40,000美元)。人口增长组的变异性也略大。这在IQR中很明显,其比 增长 组大约大50%。两个分布都呈现轻微到中度的右偏,且均为单峰。箱线图显示每组中都有许多观测值远高于中位数,不过当检查任何包含几百个以上数据点的数据集时,我们应该预期会有许多观测值落在须线之外。↩︎

  4. 答案会有所不同。并排箱线图对于比较中心和离散程度特别有用,而空心直方图更适合观察分布的形状、偏度、众数以及潜在的异常值。↩︎

  5. 山脊图让我们能更好地了解数据的形状,尤其是其众数特征。↩︎

  6. 无论位置如何(是否为都市区)或人口变化如何,从仅有高中学历的人群,到上过一些大学的人群,再到拥有学士学位的人群,家庭收入中位数似乎都在增加。↩︎

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

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

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

  10. flights 本练习中使用的数据可在 nycflights13 R 包中找到。↩︎

  11. 这一悖论被称为辛普森悖论,将在 第3章.↩︎

  12. 这一悖论被称为辛普森悖论,将在 第3章.↩︎