13. Exploratory Data Analysis#

13.1. Introduction#

This chapter will show you how to use visualisation and transformation to explore your data in a systematic way, a task that data scientists call exploratory data analysis, or EDA for short. EDA is an iterative cycle; you:

  1. Generate questions about your data.

  2. Search for answers by visualising, transforming, and modelling your data.

  3. Use what you learn to refine your questions and/or generate new questions.

EDA is not a formal process with a strict set of rules and, during the initial phases of EDA, you should feel free to investigate every idea that occurs to you. Some of these ideas will pan out, and some will be dead ends. As your exploration continues, you will home in on a few particularly productive areas that you’ll eventually write up and communicate to others. As you explore your data, you should remember that there are some pitfalls: you should always think about how the data were collected, what might be missing, whether there are quality problems, and be really strict about the differences between correlation and causation (this is a huge topic in itself!).

13.1.1. Prerequisites#

For doing EDA, we’ll use the pandas, skimpy, and pandas-profiling packages. We’ll also need lets-plot for data visualisation. All of these can be installed via pip install <packagename>.

As ever, we begin by loading these packages that we’ll use:

from skimpy import skim
import pandas as pd
from pandas.api.types import CategoricalDtype
from lets_plot import *
from lets_plot.mapping import as_discrete


13.2. Questions#

“There are no routine statistical questions, only questionable statistical routines.” — Sir David Cox

“Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise.” — John Tukey

Your goal during EDA is to develop an understanding of your data. The easiest way to do this is to use questions as tools to guide your investigation. When you ask a question, the question focuses your attention on a specific part of your dataset and helps you decide which graphs, models, or transformations to make.

EDA is fundamentally a creative process. And like most creative processes, the key to asking quality questions is to generate a large quantity of questions. It is difficult to ask revealing questions at the start of your analysis because you do not know what insights are contained in your dataset. On the other hand, each new question that you ask will expose you to a new aspect of your data and increase your chance of making a discovery. You can quickly drill down into the most interesting parts of your data—and develop a set of thought-provoking questions—if you follow up each question with a new question based on what you find.

There is no rule about which questions you should ask to guide your research. However, two types of questions will always be useful for making discoveries within your data. You can loosely word these questions as:

  1. What type of variation occurs within my variables?

  2. What type of covariation occurs between my variables?

The rest of this chapter will look at these two questions. We’ll explain what variation and covariation are, and we’ll show you several ways to answer each question.

13.3. Variation#

Variation is the tendency of the values of a variable to change from measurement to measurement. You can see variation easily in real life; if you measure any continuous variable twice, you will get two different results. This is true even if you measure quantities that are constant, like the speed of light, because of deficiencies in equipment. Each of your measurements includes a small amount of error that varies from measurement to measurement. Variables can also vary if you measure across different subjects (e.g. the eye colours of different people) or different times (e.g. the energy levels of an electron at different moments). The best way to understand that pattern is to visualize the distribution of the variable’s values.

We’ll start our exploration by visualizing the distribution of weights ("carat") of ~54,000 diamonds from the diamonds dataset.

diamonds = pd.read_csv(
diamonds["cut"] = diamonds["cut"].astype(
        categories=["Fair", "Good", "Very Good", "Premium", "Ideal"], ordered=True
diamonds["color"] = diamonds["color"].astype(
    CategoricalDtype(categories=["D", "E", "F", "G", "H", "I", "J"], ordered=True)
carat cut color clarity depth table price x y z
0 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
1 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
2 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
3 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
4 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75

Since "carat" is a numerical variable, we can use a histogram:

(ggplot(diamonds, aes(x="carat")) + geom_histogram(binwidth=0.5))

Now that you can visualize variation, what should you look for in your plots? And what type of follow-up questions should you ask? We’ve put together a list below of the most useful types of information that you will find in your graphs, along with some follow-up questions for each type of information. The key to asking good follow-up questions will be to rely on your curiosity (What do you want to learn more about?) as well as your skepticism (How could this be misleading?).

13.3.1. Typical values#

In both bar charts and histograms, tall bars show the common values of a variable, and shorter bars show less-common values. Places that do not have bars reveal values that were not seen in your data. To turn this information into useful questions, look for anything unexpected:

  • Which values are the most common? Why?

  • Which values are rare? Why? Does that match your expectations?

  • Can you see any unusual patterns? What might explain them?

Let’s take a look at the distribution of "carat" for smaller diamonds.

Note that when we create smaller_diamonds, we’re doing it by creating a copy. Otherwise, any changes we made to smaller_diamonds would also affect diamonds (the two point to the same underlying data in your computer’s memory). Sometimes you may want to have a cut still be connected to the original dataset, and sometimes you don’t; in this case, we’d like them to be distinct so we use copy().

smaller_diamonds = diamonds.query("carat < 3").copy()

(ggplot(smaller_diamonds, aes(x="carat")) + geom_histogram(binwidth=0.01))

This histogram suggests several interesting questions:

  • Why are there more diamonds at whole carats and common fractions of carats?

  • Why are there more diamonds slightly to the right of each peak than there are slightly to the left of each peak?

Visualisations can also reveal clusters, which suggest that subgroups exist in your data. To understand the subgroups, ask:

  • How are the observations within each subgroup similar to each other?

  • How are the observations in separate clusters different from each other?

  • How can you explain or describe the clusters?

  • Why might the appearance of clusters be misleading?

Some of these questions can be answered with the data while some will require domain expertise about the data. Many of them will prompt you to explore a relationship between variables, for example, to see if the values of one variable can explain the behavior of another variable. We’ll get to that shortly.

13.3.2. Unusual values#

Outliers are observations that are unusual; data points that don’t seem to fit the pattern. Sometimes outliers are data entry errors, sometimes they are simply values at the extremes that happened to be observed in this data collection, and other times they suggest important new discoveries. When you have a lot of data, outliers are sometimes difficult to see in a histogram. For example, take the distribution of the "y" variable from the diamonds dataset. The only evidence of outliers is the unusually wide limits on the x-axis.

(ggplot(diamonds, aes(x="y")) + geom_histogram(binwidth=0.5))

There are so many observations in the common bins that the rare bins are very short, making it very difficult to see them (although maybe if you stare intently at 0 you’ll spot something). To make it easy to see the unusual values, we need to zoom to small values of the y-axis with coord_cartesian():

    ggplot(diamonds, aes(x="y"))
    + geom_histogram(binwidth=0.5)
    + coord_cartesian(ylim=[0, 50])

coord_cartesian() also has an xlim() argument for when you need to zoom into the x-axis. Lets-Plot also has xlim() and ylim() functions that work slightly differently: they throw away the data outside the limits.

This allows us to see that there are three unusual values: 0, ~30, and ~60. We pluck them out with pandas:

unusual = diamonds.query("y < 3 or y > 20").loc[:, ["x", "y", "z", "price"]]
x y z price
11963 0.00 0.0 0.00 5139
15951 0.00 0.0 0.00 6381
24067 8.09 58.9 8.06 12210
24520 0.00 0.0 0.00 12800
26243 0.00 0.0 0.00 15686
27429 0.00 0.0 0.00 18034
49189 5.15 31.8 5.12 2075
49556 0.00 0.0 0.00 2130
49557 0.00 0.0 0.00 2130

The "y" variable measures one of the three dimensions of these diamonds, in mm. We know that diamonds can’t have a width of 0mm, so these values must be incorrect. By doing EDA, we have discovered missing data that was coded as 0, which we never would have found by simply searching for NAs. Going forward we might choose to re-code these values as NAs in order to prevent misleading calculations. We might also suspect that measurements of 32mm and 59mm are implausible: those diamonds are over an inch long, but don’t cost hundreds of thousands of dollars!

It’s good practice to repeat your analysis with and without the outliers. If they have minimal effect on the results, and you can’t figure out why they’re there, it’s reasonable to omit them, and move on. However, if they have a substantial effect on your results, you shouldn’t drop them without justification. You’ll need to figure out what caused them (e.g., a data entry error) and disclose that you removed them in your write-up.

13.3.3. Exercises#

  1. Explore the distribution of each of the x, y, and z variables in diamonds. What do you learn? Think about a diamond and how you might decide which dimension is the length, width, and depth.

  2. Explore the distribution of "price". Do you discover anything unusual or surprising? (Hint: Carefully think about the binwidth= keyword argument setting and make sure you try a wide range of values.)

  3. How many diamonds are 0.99 carat? How many are 1 carat? What do you think is the cause of the difference?

  4. Compare and contrast coord_cartesian() vs. xlim() or ylim() when zooming in on a histogram. What happens if you leave binwidth unset? What happens if you try and zoom so only half a bar shows?

13.4. Unusual Values#

If you’ve encountered unusual values in your dataset, and simply want to move on to the rest of your analysis, you have two options.

  1. Drop the entire row with the strange values:

    condition = ((diamonds["y"] < 3) | (diamonds["y"] > 20))
    diamonds2 = diamonds.loc[~condition, :]

    We don’t recommend this option because one invalid value doesn’t imply that all the other values for that observation are also invalid. Additionally, if you have low quality data, by the time that you’ve applied this approach to every variable you might find that you don’t have any data left!

  2. Instead, we recommend replacing the unusual values with missing values. One way to do this, which makes a distinction between data frames that have had the unusual values replaced and the original data, is to make a copy and then set the problematic values to pd.NA, pandas’s special NA value.

diamonds2 = diamonds.copy()
condition = (diamonds2["y"] < 3) | (diamonds2["y"] > 20)
diamonds2.loc[condition, "y"] = pd.NA

It’s not obvious where you should plot missing values, so lets-plot doesn’t include them in the plot:

(ggplot(diamonds2, aes(x="x", y="y")) + geom_point())

Other times you want to understand what makes observations with missing values different to observations with recorded values. For example, in the nycflights13 data, missing values in the "dep_time" variable indicate that the flight was cancelled. So you might want to compare the scheduled departure times for cancelled and non-cancelled times. You can do this by making a new variable, using is.na() to check if "dep_time" is missing.

url = "https://raw.githubusercontent.com/byuidatascience/data4python4ds/master/data-raw/flights/flights.csv"
flights = pd.read_csv(url)
year month day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin dest air_time distance hour minute time_hour
0 2013 1 1 517.0 515 2.0 830.0 819 11.0 UA 1545 N14228 EWR IAH 227.0 1400 5 15 2013-01-01T10:00:00Z
1 2013 1 1 533.0 529 4.0 850.0 830 20.0 UA 1714 N24211 LGA IAH 227.0 1416 5 29 2013-01-01T10:00:00Z
2 2013 1 1 542.0 540 2.0 923.0 850 33.0 AA 1141 N619AA JFK MIA 160.0 1089 5 40 2013-01-01T10:00:00Z
3 2013 1 1 544.0 545 -1.0 1004.0 1022 -18.0 B6 725 N804JB JFK BQN 183.0 1576 5 45 2013-01-01T10:00:00Z
4 2013 1 1 554.0 600 -6.0 812.0 837 -25.0 DL 461 N668DN LGA ATL 116.0 762 6 0 2013-01-01T11:00:00Z
flights2 = flights.assign(
    cancelled=lambda x: pd.isna(x["dep_time"]),
    sched_hour=lambda x: x["sched_dep_time"] // 100,
    sched_min=lambda x: x["sched_dep_time"] % 100,
    sched_dep_time=lambda x: x["sched_hour"] + x["sched_min"] / 60,

    ggplot(flights2, aes(x="sched_dep_time"))
    + geom_freqpoly(aes(color="cancelled"), binwidth=1 / 4)

However this plot isn’t great because there are many more non-cancelled flights than cancelled flights. In the next section we’ll explore some techniques for improving this comparison.

13.4.1. Exercises#

  1. What happens to missing values in a histogram? What happens to missing values in a bar chart? Why is there a difference in how missing values are handled in histograms and bar charts?

  2. Recreate the frequency plot of scheduled_dep_time coloured by whether the flight was cancelled or not. Also facet by the cancelled variable. Experiment with different values of the scales variable in the faceting function to mitigate the effect of more non-cancelled flights than cancelled flights.

13.5. Covariation#

If variation describes the behavior within a variable, covariation describes the behavior between variables. Covariation is the tendency for the values of two or more variables to vary together in a related way. The best way to spot covariation is to visualise the relationship between two or more variables, but note that covariation doesn’t imply a causal relationship between variables.

13.5.1. A categorical and a numerical variable#

For example, let’s explore how the price of a diamond varies with its quality (measured by "cut") using geom_freqpoly():

    ggplot(diamonds, aes(x="price"))
    + geom_freqpoly(aes(color="cut"), binwidth=500, linewidth=0.75)

The default appearance of geom_freqpoly() is not that useful here because the height, determined by the overall count, differs so much across cuts, making it hard to see the differences in the shapes of their distributions.

To make the comparison easier we need to swap what is displayed on the y-axis. Instead of displaying count, we’ll display the density, which is the count standardised so that the area under each frequency polygon is one.

    ggplot(diamonds, aes(x="price"))
    + geom_density(aes(color="cut", fill="cut"), size=1, alpha=0.2)

There’s something rather surprising about this plot - it appears that fair diamonds (the lowest quality) have the highest average price! But maybe that’s because density plots are a little hard to interpret - there’s a lot going on in this plot.

A visually simpler plot for exploring this relationship is using side-by-side boxplots.

(ggplot(diamonds, aes(x="cut", y="price")) + geom_boxplot())

We see much less information about the distribution, but the boxplots are much more compact so we can more easily compare them (and fit more on one plot). It supports the counter-intuitive finding that better quality diamonds are typically cheaper! In the exercises, you’ll be challenged to figure out why.

"cut" is an ordered categorical variable: fair is worse than good, which is worse than very good and so on. Many categorical variables don’t have such an intrinsic order, so you might want to reorder them to make a more informative display. One way to do that is according to the median value, though other options are available.

As an example, with the mpg dataset, we might want to look at how highway mileage varies across classes:

mpg = pd.read_csv(
    "https://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/mpg.csv", index_col=0
mpg["class"] = mpg["class"].astype("category")

(ggplot(mpg, aes(x="class", y="hwy")) + geom_boxplot())

To make the trend easier to see, we can reorder class based on the median value of "hwy":

(ggplot(mpg) + geom_boxplot(aes(as_discrete("class", order_by="..middle.."), "hwy")))

If you have long variable names, geom_boxplot() will work better if you flip it 90°. You can do that by adding coord_flip().

    + geom_boxplot(aes(as_discrete("class", order_by="..middle.."), "hwy"))
    + coord_flip()
) Exercises#

  1. Use what you’ve learned to improve the visualisation of the departure times of cancelled vs. non-cancelled flights.

  2. Based on EDA, what variable in the diamonds dataset appears to be most important for predicting the price of a diamond? How is that variable correlated with cut? Why does the combination of those two relationships lead to lower quality diamonds being more expensive?

  3. Create a visualisation of diamond prices vs. a categorical variable from the diamonds dataset using geom_violin(), then a faceted geom_histogram(), then a coloured geom_freqpoly(), and then a coloured geom_density(). Compare and contrast the four plots. What are the pros and cons of each method of visualising the distribution of a numerical variable based on the levels of a categorical variable?

  4. If you have a small dataset, it’s sometimes useful to use geom_jitter() to avoid overplotting to more easily see the relationship between a continuous and categorical variable. The ggbeeswarm package provides a number of methods similar to geom_jitter(). List them and briefly describe what each one does.

13.5.2. Two categorical variables#

To visualise the covariation between categorical variables, you’ll need to count the number of observations for each combination of levels of these categorical variables. You can do this with a pd.crosstab() that we then melt to put it in “tidy” format.

ct_cut_color = pd.melt(
    pd.crosstab(diamonds["cut"], diamonds["color"]).reset_index(),

Followed by visualising it with geom_tile():

(ggplot(ct_cut_color, aes(x="color", y="cut")) + geom_tile(aes(fill="value")))

13.5.3. Exercises#

  1. How could you rescale the count dataset above to more clearly show the distribution of cut within color, or colour within cut?

  2. What different data insights do you get with a segmented bar chart if colour is mapped to the x aesthetic and cut is mapped to the fill aesthetic? Calculate the counts that fall into each of the segments.

  3. Use geom_tile() together with pandas to explore how average flight departure delays vary by destination and month of year. What makes the plot difficult to read? How could you improve it?

13.5.4. Two numerical variables#

You’ve already seen one great way to visualise the covariation between two numerical variables: draw a scatterplot with geom_point(). You can see covariation as a pattern in the points. For example, you can see a positive association between the carat size and price of a diamond: diamonds with more carats have a higher price. The relationship is exponential.

(ggplot(smaller_diamonds, aes(x="carat", y="price")) + geom_point())