Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

15.1 Correlation

In this section we will develop a measure of how tightly clustered a scatter diagram is about a straight line. Formally, this is called measuring linear association.

The table hybrid contains data on hybrid passenger cars sold in the United States from 1997 to 2013. The data were adapted from the online data archive of Prof. Larry Winner of the University of Florida. The columns:

  • vehicle: model of the car

  • year: year of manufacture

  • msrp: manufacturer’s suggested retail price in 2013 dollars

  • acceleration: acceleration rate in km per hour per second

  • mpg: fuel econonmy in miles per gallon

  • class: the model’s class.

hybrid = Table.read_table(path_data + 'hybrid.csv')
hybrid
Loading...

The graph below is a scatter plot of msrp versus acceleration. That means msrp is plotted on the vertical axis and accelaration on the horizontal.

hybrid.scatter('acceleration', 'msrp')
Scatterplot with 'acceleration' on the x-axis and 'msrp' on the y-axis. Generally there is a positive assocation; as the x value increases so does the y value. As the x value increases there are fewere data points and trend is a little less clear.

Notice the positive association. The scatter of points is sloping upwards, indicating that cars with greater acceleration tended to cost more, on average; conversely, the cars that cost more tended to have greater acceleration on average.

The scatter diagram of MSRP versus mileage shows a negative association. Hybrid cars with higher mileage tended to cost less, on average. This seems surprising till you consider that cars that accelerate fast tend to be less fuel efficient and have lower mileage. As the previous scatter plot showed, those were also the cars that tended to cost more.

hybrid.scatter('mpg', 'msrp')
Scatterplot with 'mpg' on the x-axis and 'msrp' on the y-axis. The x-axis ranges from about x=20 to about x=70. There is a non-linear association between x and y values. On the left hand side of the graph, there appears to be a weak negative assocation, but above x=40, there is no clear association between x and y values, however the y values remain small.

Along with the negative association, the scatter diagram of price versus efficiency shows a non-linear relation between the two variables. The points appear to be clustered around a curve, not around a straight line.

If we restrict the data just to the SUV class, however, the association between price and efficiency is still negative but the relation appears to be more linear. The relation between the price and acceleration of SUV’s also shows a linear trend, but with a positive slope.

suv = hybrid.where('class', 'SUV')
suv.scatter('mpg', 'msrp')
Scatterplot with 'mpg' on the x-axis and 'msrp' on the y-axis. There is a clear negative association; as the x value increases, the y value decreases.
suv.scatter('acceleration', 'msrp')
Scatterplot with 'acceleration' on the x-axis and 'msrp' on the y-axis. There appears to be a postive association; as x increases so does y. There are some obvious outliers.

You will have noticed that we can derive useful information from the general orientation and shape of a scatter diagram even without paying attention to the units in which the variables were measured.

Indeed, we could plot all the variables in standard units and the plots would look the same. This gives us a way to compare the degree of linearity in two scatter diagrams.

Recall that in an earlier section we defined the function standard_units to convert an array of numbers to standard units.

def standard_units(any_numbers):
    "Convert any array of numbers to standard units."
    return (any_numbers - np.mean(any_numbers))/np.std(any_numbers)  

We can use this function to re-draw the two scatter diagrams for SUVs, with all the variables measured in standard units.

Table().with_columns(
    'mpg (standard units)',  standard_units(suv.column('mpg')), 
    'msrp (standard units)', standard_units(suv.column('msrp'))
).scatter(0, 1)
plots.xlim(-3, 3)
plots.ylim(-3, 3);
Scatterplot with 'mpg (standard units)' on the x-axis and 'msrp (standard units)' on the y-axis. There is a clear negative association; as the x value increases, the y value decreases.
Table().with_columns(
    'acceleration (standard units)', standard_units(suv.column('acceleration')), 
    'msrp (standard units)',         standard_units(suv.column('msrp'))
).scatter(0, 1)
plots.xlim(-3, 3)
plots.ylim(-3, 3);
Scatterplot with 'acceleration (standard units)' on the x-axis and 'msrp (standard units)' on the y-axis. There tends to be a positive assocation; as the x value increases so does the y value. There are some notable outliers around x=-1.8 and x=-0.7 which have higher y values than other data points with similar x values.

The associations that we see in these figures are the same as those we saw before. Also, because the two scatter diagrams are now drawn on exactly the same scale, we can see that the linear relation in the second diagram is a little more fuzzy than in the first.

We will now define a measure that uses standard units to quantify the kinds of association that we have seen.

15.1.1The correlation coefficient

The correlation coefficient measures the strength of the linear relationship between two variables. Graphically, it measures how clustered the scatter diagram is around a straight line.

The term correlation coefficient isn’t easy to say, so it is usually shortened to correlation and denoted by rr.

Here are some mathematical facts about rr that we will just observe by simulation.

  • The correlation coefficient rr is a number between -1 and 1.

  • rr measures the extent to which the scatter plot clusters around a straight line.

  • r=1r = 1 if the scatter diagram is a perfect straight line sloping upwards, and r=1r = -1 if the scatter diagram is a perfect straight line sloping downwards.

The function r_scatter takes a value of rr as its argument and simulates a scatter plot with a correlation very close to rr. Because of randomness in the simulation, the correlation is not expected to be exactly equal to rr.

Call r_scatter a few times, with different values of rr as the argument, and see how the scatter plot changes.

When r=1r=1 the scatter plot is perfectly linear and slopes upward. When r=1r=-1, the scatter plot is perfectly linear and slopes downward. When r=0r=0, the scatter plot is a formless cloud around the horizontal axis, and the variables are said to be uncorrelated.

r_scatter(0.9)
Scatterplot showing a clear positive association. The data points are closely grouped and as the x value increases, so does the y value.
r_scatter(0.25)
Scatterplot with weak positive association. Most data points are in a blob, but you can see around the edges that as the x value increases so does the y value.
r_scatter(0)
Scatterplot showing no association. Unlike the previous graph there is no pattern within the bulk of the data or around the edges.
r_scatter(-0.55)
Scatterplot with negative association; as x values increase the y values tend to decrease. The data points are somewhat blob-like, but have a clear association.

15.1.2Calculating rr

The formula for rr is not apparent from our observations so far. It has a mathematical basis that is outside the scope of this class. However, as you will see, the calculation is straightforward and helps us understand several of the properties of rr.

Formula for rr:

rr is the average of the products of the two variables, when both variables are measured in standard units.

Here are the steps in the calculation. We will apply the steps to a simple table of values of xx and yy.

x = np.arange(1, 7, 1)
y = make_array(2, 3, 1, 5, 2, 7)
t = Table().with_columns(
        'x', x,
        'y', y
    )
t
Loading...

Based on the scatter diagram, we expect that rr will be positive but not equal to 1.

t.scatter(0, 1, s=30, color='red')
Scatterplot where there is one data point per integer x value. The x-axis is labeled 'x' and y-axis is labeled 'y.' The data points are at (1, 2), (2, 3), (3, 1), (4, 5), (5, 2), and (6, 7).

Step 1. Convert each variable to standard units.

t_su = t.with_columns(
        'x (standard units)', standard_units(x),
        'y (standard units)', standard_units(y)
    )
t_su
Loading...

Step 2. Multiply each pair of standard units.

t_product = t_su.with_column('product of standard units', t_su.column(2) * t_su.column(3))
t_product
Loading...

Step 3. rr is the average of the products computed in Step 2.

# r is the average of the products of standard units

r = np.mean(t_product.column(4))
r
0.6174163971897709

As expected, rr is positive but not equal to 1.

15.1.3Properties of rr

The calculation shows that:

  • rr is a pure number. It has no units. This is because rr is based on standard units.

  • rr is unaffected by changing the units on either axis. This too is because rr is based on standard units.

  • rr is unaffected by switching the axes. Algebraically, this is because the product of standard units does not depend on which variable is called xx and which yy. Geometrically, switching axes reflects the scatter plot about the line y=xy=x, but does not change the amount of clustering nor the sign of the association.

t.scatter('y', 'x', s=30, color='red')
Scatterplot where there is one data point per integer x value, except 4 and 6. This time the x-axis is labeled 'y' and the y-axis is labeled 'x.' Data points are at (1, 3), (2, 5), (3, 2), (5, 4), and (7, 6).

15.1.4The correlation function

We are going to be calculating correlations repeatedly, so it will help to define a function that computes it by performing all the steps described above. Let’s define a function correlation that takes a table and the labels of two columns in the table. The function returns rr, the mean of the products of those column values in standard units.

def correlation(t, x, y):
    return np.mean(standard_units(t.column(x))*standard_units(t.column(y)))

Let’s call the function on the x and y columns of t. The function returns the same answer to the correlation between xx and yy as we got by direct application of the formula for rr.

correlation(t, 'x', 'y')
0.6174163971897709

As we noticed, the order in which the variables are specified doesn’t matter.

correlation(t, 'y', 'x')
0.6174163971897709

Calling correlation on columns of the table suv gives us the correlation between price and mileage as well as the correlation between price and acceleration.

correlation(suv, 'mpg', 'msrp')
-0.6667143635709919
correlation(suv, 'acceleration', 'msrp')
0.48699799279959155

These values confirm what we had observed:

  • There is a negative association between price and efficiency, whereas the association between price and acceleration is positive.

  • The linear relation between price and acceleration is a little weaker (correlation about 0.5) than between price and mileage (correlation about -0.67).

Correlation is a simple and powerful concept, but it is sometimes misused. Before using rr, it is important to be aware of what correlation does and does not measure.

15.1.5Association is not Causation

Correlation only measures association. Correlation does not imply causation. Though the correlation between the weight and the math ability of children in a school district may be positive, that does not mean that doing math makes children heavier or that putting on weight improves the children’s math skills. Age is a confounding variable: older children are both heavier and better at math than younger children, on average.

15.1.6Correlation Measures Linear Association

Correlation measures only one kind of association – linear. Variables that have strong non-linear association might have very low correlation. Here is an example of variables that have a perfect quadratic relation y=x2y = x^2 but have correlation equal to 0.

new_x = np.arange(-4, 4.1, 0.5)
nonlinear = Table().with_columns(
        'x', new_x,
        'y', new_x**2
    )
nonlinear.scatter('x', 'y', s=30, color='r')
Scatterplot with the x-axis labeled 'x' and the y-axis labeled 'y.' The data displays a nonlinear U-shaped pattern with the lowest y value at x=0.
correlation(nonlinear, 'x', 'y')
0.0

15.1.7Correlation is Affected by Outliers

Outliers can have a big effect on correlation. Here is an example where a scatter plot for which rr is equal to 1 is turned into a plot for which rr is equal to 0, by the addition of just one outlying point.

line = Table().with_columns(
        'x', make_array(1, 2, 3, 4),
        'y', make_array(1, 2, 3, 4)
    )
line.scatter('x', 'y', s=30, color='r')
Scatterplot with the x-axis labeled 'x' and y-axis labeled 'y.' Data points are at (1, 1), (2, 2), (3, 3), and (4, 4).
correlation(line, 'x', 'y')
1.0
outlier = Table().with_columns(
        'x', make_array(1, 2, 3, 4, 5),
        'y', make_array(1, 2, 3, 4, 0)
    )
outlier.scatter('x', 'y', s=30, color='r')
Scatterplot with the x-axis labeled 'x' and y-axis labeled 'y.' Data points are at (1, 1), (2, 2), (3, 3), (4, 4), and (5, 0).
correlation(outlier, 'x', 'y')
0.0

15.1.8Ecological Correlations Should be Interpreted with Care

Correlations based on aggregated data can be misleading. As an example, here are data on the Critical Reading and Math SAT scores in 2014. There is one point for each of the 50 states and one for Washington, D.C. The column Participation Rate contains the percent of high school seniors who took the test. The next three columns show the average score in the state on each portion of the test, and the final column is the average of the total scores on the test.

sat2014 = Table.read_table(path_data + 'sat2014.csv').sort('State')
sat2014
Loading...

The scatter diagram of Math scores versus Critical Reading scores is very tightly clustered around a straight line; the correlation is close to 0.985.

sat2014.scatter('Critical Reading', 'Math')
Scatterplot with 'Critical Reading' on the x-axis and 'Math' on the y-axis. There is a positive correlation; as x values increase, so do the y values. There are no outliers.
correlation(sat2014, 'Critical Reading', 'Math')
0.9847558411067434

That’s an extremely high correlation. But it’s important to note that this does not reflect the strength of the relation between the Math and Critical Reading scores of students.

The data consist of average scores in each state. But states don’t take tests – students do. The data in the table have been created by lumping all the students in each state into a single point at the average values of the two variables in that state. But not all students in the state will be at that point, as students vary in their performance. If you plot a point for each student instead of just one for each state, there will be a cloud of points around each point in the figure above. The overall picture will be more fuzzy. The correlation between the Math and Critical Reading scores of the students will be lower than the value calculated based on state averages.

Correlations based on aggregates and averages are called ecological correlations and are frequently reported. As we have just seen, they must be interpreted with care.

15.1.9Serious or tongue-in-cheek?

In 2012, a paper in the respected New England Journal of Medicine examined the relation between chocolate consumption and Nobel Prizes in a group of countries. The Scientific American responded seriously whereas others were more relaxed. You are welcome to make your own decision! The following graph, provided in the paper, should motivate you to go and take a look.

A stylized scatterplot with 'Chocolate Consumption kg/yr/capita' on the x-axis and 'Nobel Laureates per 10 Million Population' on the y-axis. The graph is annotated with 'r=0.791' and 'P<0.0001.' We generally see a positive correlation; as the x value increases so does the y value. In the bottom left we see China, Japan, Portugal, Brazil, and Greece. The United States, France, and Finland have the largest x values among the cluster in Quadrant III (x<7). Countries with y values greater than 15 are the United Kingdom, Norway, Austria, Denmark, Sweden, and Switzerland. Sweden has a much higher y value (y~31) than other countries with similar x values (x~6). Ireland and Germany have high x values (approx 9 and 11 respectively) with low y values (y~13)compared to other countires with similar x values.