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.
loan50 dataset from Chapter 1 represents a sample from a larger loan dataset called
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
mortgage (owns but has a mortgage), or
app_type, which indicates whether the loan application was made with a partner or whether it was an individual application.
loans_full_schema data can be found in the openintro R package.
Based on the data in this dataset we have modified the
We will refer to this modified dataset as
Table 4.1 summarizes two variables:
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
A bar plot is a common way to display a single categorical variable.
The left panel of Figure 4.1 shows a bar plot for the
In the right panel, the counts are converted into proportions, showing the proportion of observations that are in each level.
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 the relationship between
Plot A in Figure 4.2 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.
Plot B is a dodged bar plot.
This plot most clearly displays that within each level of homeownership, individual applications are more common than joint applications.
Finally, plot C is a standardized bar plot (also known as filled bar plot).
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.
This type of visualization is helpful in understanding the fraction of individual or joint loan applications for borrowers in each level of
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.
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.
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 Plot A of Figure 4.3.
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.
Plot B in Figure 4.3 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
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.
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.
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.
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
own), this provides evidence that
homeownership variables may be associated.
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
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.
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 whether the email contains no numbers, small numbers, or big numbers. Another characteristic is the email format, which indicates whether or not 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.
None that we think are obvious! What is distinct about the email example is that the two loan variables don’t 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.
A pie chart is shown in Figure 4.5 alongside a bar plot representing the same information. 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.
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 and the bar plot in Figure 4.6 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.
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 displays two examples of waffle charts: one for the distribution of homeownership and the other for the distribution of loan status.
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’ve 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 5 observations from each group.
|State||County||Population change (%)||Gain / No gain||Median household income|
|Washington||Grays Harbor County||2.30||gain||45483|
|Alabama||Conecuh County||-3.40||no gain||30434|
|Illinois||McDonough County||-4.32||no gain||42911|
|Iowa||Iowa County||-1.08||no gain||58077|
|Michigan||Genesee County||-1.95||no gain||45231|
|Wyoming||Campbell County||-3.76||no gain||80178|
Color can be used to split histograms for numerical variables by levels of a categorical variable. An example of this is shown in Plot A of Figure 4.8. The side-by-side box plot is another traditional tool for comparing across groups. An example is shown in Plot B of Figure 4.8, where there are two box plots, one for each group, placed into one plotting window and drawn on the same scale.
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?43
Another useful visualization for comparing numerical data across groups is a ridge plot, which combines 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.
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.
Plot A in Figure 4.10 displays the same information as Plot A in Figure 4.8, 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 Plot B in Figure 4.10 we have now split the data into four groups using the
- 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.
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.
Fluently working with categorical variables is an important skill for data analysts. In this chapter we’ve 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.
We introduced the following terms in the chapter. If you’re not sure what some of these terms mean, we recommend you go back in the text and review their definitions. We are purposefully presenting them in alphabetical order, instead of in order of appearance, so they will be a little more challenging to locate. However you should be able to easily spot them as bolded text.
|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|
Answers to odd numbered exercises can be found in Appendix A.4.
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.47
What features are apparent in the bar plot but not in the pie chart?
What features are apparent in the pie chart but not in the bar plot?
Which graph would you prefer to use for displaying these categorical data?
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.48
Apply for citizenship
Leave the country
What percent of these Tampa, FL voters identify themselves as conservatives?
What percent of these Tampa, FL voters are in favor of the citizenship option?
What percent of these Tampa, FL voters identify themselves as conservatives and are in favor of the citizenship option?
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?
Do political ideology and views on immigration appear to be associated? Explain your reasoning.
Conjecture other possible variables that might explain the potential relationship between these two variables.
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.
Based on the stacked bar plot, do views on the protests and age appear to be associated? Explain your reasoning.
Conjecture other possible variables that might explain the potential association between these two variables.
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. (Public Policy Polling 2015)
Based on the stacked bar plot shown above, do views on raising taxes and political affiliation appear to be associated? Explain your reasoning.
Conjecture other possible variables that might explain the potential association between these two variables.
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 he was 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 visualization below displays two different versions of the data.49 (Turnbull, Brown, and Hu 1974)
Provide one aspect of the two group comparison that is easier to see from the stacked bar plot (left)?
Provide one aspect of the two group comparison that is easeir to see from the standardized bar plot (right)?
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?
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 table below shows the distribution of responses by age group as well as the expected counts for each cell (shown in italics).
Which graph (top or bottom) would you use to understand the shipping choices of people of different ages?
Which graph (top or bottom) would you use to understand the age distribution across different types of shipping choices?
A new shipping company would like to market to people over the age of 55. Who will be their biggest competitor?
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?