Weeks
Statistics 1Week 4 · Association: Contingency Tables, Scatter Plots, Correlation and Fitted Lines
Week 4 Notes

Statistics for
Data Science 1

Association between variables: contingency tables, relative frequencies, scatter plots, covariance, correlation and fitted lines.

11 chapters~35 min read
Contingency tablesScatter plotsCovariance and correlationFitted lines and R²

Chapters

  1. 01Contingency TablesLectures 4.1 and 4.2
  2. 02Relative FrequenciesLecture 4.3
  3. 03Is There an Association?Lecture 4.3
  4. 04Stacked Bar ChartsLecture 4.3
  5. 05Scatter PlotsLecture 4.4
  6. 06Describing AssociationLecture 4.5
  7. 07CovarianceLecture 4.6
  8. 08CorrelationLecture 4.7
  9. 09Fitting a LineLectures 4.7 and 4.8
  10. 10Categorical and Numerical VariablesLecture 4.9
  11. 11Week 4 Summary SheetAll lectures

Based on lectures by Usha Mohan, IIT Madras

01
Lectures 4.1 and 4.2

Contingency Tables

Weeks 1 to 3 described one variable at a time. Week 4 asks whether two variables are connected. The lecture opens with a review of the course so far.

1.1Where this fits and the three objectives

Review: Weeks 1 to 3
  • What is statistics: descriptive and inferential statistics.
  • How data are collected: variables and cases (observations).
  • Types of data: categorical or numerical; nominal, ordinal, interval, ratio.
  • Categorical data: frequency tables, relative frequency, pie and bar charts, mode, median.
  • Numerical data: frequency tables, mean, median, mode, range, variance, SD, percentiles, IQR.
Objectives of Week 4
  • Two categorical variables: use two-way contingency tables to understand association.
  • Two numerical variables: understand association through scatter plots; compute and interpret correlation.
  • Mixed variables: understand the relationship between a categorical and a numerical variable.
Categorical and categoricalContingency tableRelative frequenciesStacked bar chartLectures 4.2 and 4.3Numerical and numericalScatter plotCovariance and correlationFitted line and R squaredLectures 4.4 to 4.8Categorical and numericalGroup the numbers by categoryPoint bi-serial correlationLecture 4.9
Figure 1. The tools of Week 4, grouped by the types of the two variables

1.2The contingency table

Definition: contingency tableData on two categorical variables can be organised in a two-way table, called a contingency table. One variable runs down the rows, the other across the columns, and each cell counts the cases with that pair of categories. The table also carries row totals, column totals and the grand total.
Gender \ Own a smartphoneNoYesRow total
Female103444
Male144256
Column total2476100
Cell
  • 34 = females who own a smartphone
Row total
  • 44 = all female students
Column total
  • 76 = all smartphone owners
Grand total
  • 100 = all students surveyed

1.3Lecture examples

Example 1: gender versus use of a smartphone

A market research firm wants to find out whether ownership of a smartphone is associated with the gender of a student: do more females own a smartphone than males, or is owning one independent of gender? A group of 100 college-going children were surveyed.

  • There are 44 female and 56 male students.
  • 76 students owned a smartphone and 24 did not.
  • 34 female students and 42 male students owned a smartphone.
  1. Identify the variables. Gender (Male, Female): 2 categories, nominal. Own a smartphone (Yes, No): 2 categories, nominal.
  2. Fill in what is given. Row totals 44 and 56; column totals 24 (No) and 76 (Yes); the Yes cells are 34 and 42.
  3. Find the missing cells by subtraction. Female No = 44 - 34 = 10; Male No = 56 - 42 = 14.
  4. Check. Column No: 10 + 14 = 24; column Yes: 34 + 42 = 76; grand total 24 + 76 = 44 + 56 = 100.
Gender \ Own a smartphoneNoYesRow total
Female103444
Male144256
Column total2476100

Example 2: income versus use of a smartphone

The firm now asks whether ownership of a smartphone is associated with income. A group of 100 randomly picked individuals were surveyed.

  • 20 High, 66 Medium and 14 Low income participants.
  • 62 owned a smartphone and 38 did not.
  • 18 High, 39 Medium and 5 Low income participants owned a smartphone.
  1. Identify the variables. Income level (Low, Medium, High): 3 categories, ordinal. Own a smartphone (Yes, No): 2 categories, nominal.
  2. Missing cells. High No = 20 - 18 = 2; Medium No = 66 - 39 = 27; Low No = 14 - 5 = 9.
  3. Check. Column No: 2 + 27 + 9 = 38; column Yes: 18 + 39 + 5 = 62; 38 + 62 = 20 + 66 + 14 = 100.
Income level \ Own a smartphoneNoYesRow total
High21820
Medium273966
Low9514
Column total3862100
Ordinal variablesIf a variable is ordinal, keep its order in the table. In Example 2 the income levels are listed High, Medium, Low, so the rows follow the order of the variable and are not shuffled.

1.4Building a contingency table in Google Sheets

  1. Choose the columns of the variables for which you seek an association.
  2. Go to Data and click the Pivot table option.
  3. Click Create; this opens the pivot table editor.
  4. Under Rows, click the first categorical variable.
  5. Under Columns, click the second categorical variable.
  6. Under Values, click either of the variables, then choose COUNTA under “Summarize by”.

1.5Going deeper: reading a contingency table

  1. Every case sits in exactly one cell. That is why the cells add up to the grand total (here 100).
  2. Totals are the one-variable tables. The row-total column is the frequency table of the row variable alone; the column-total row is the frequency table of the column variable alone. These two are called the marginal totals (an extra term, not from the lecture).
  3. Subtraction is the shortcut. When a total and one cell are given, the other cell in that row is the difference. Always finish with the column check.
  4. Which variable goes on the rows? Either works. In these notes the variable whose groups you want to compare (gender, income) goes down the rows.
Exam tips
  • Write the totals first, then fill the cells.
  • Check every row and every column, and the grand total.
  • Do not reorder an ordinal variable.
Common mistakes
  • Putting the same count in two cells.
  • Mixing up a cell with a total.
  • Forgetting to keep the order of Low, Medium, High.
Next · Lecture 4.3Relative Frequencies
02
Lecture 4.3

Relative Frequencies

Raw counts are hard to compare when the groups have different sizes. Two questions show why: What proportion of all participants own a smartphone? and What proportion of the female participants own a smartphone? The second question divides by the number of females, not by 100.

Definition: row relative frequencyRow relative frequency: divide each cell frequency in a row by its row total.
Definition: column relative frequencyColumn relative frequency: divide each cell frequency in a column by its column total.
Row relative frequency
3444\frac{34}{44}

divide the cell by its row total

Column relative frequency
3476\frac{34}{76}

divide the cell by its column total

2.1Row relative frequencies: lecture examples

Example 3: gender and smartphone

  1. Divide every cell by the total of its row (44 for Female, 56 for Male). The column-total row is divided by the grand total, 100.
  2. Convert to percentages.
Gender \ Own a smartphoneNoYesRow total
Female10/4434/4444
Male14/5642/5656
Column total24/10076/100100
Gender \ Own a smartphoneNoYesRow total
Female22.73%77.27%44
Male25.00%75.00%56
Column total24.00%76.00%100
Reading it

77.27% of the female students own a smartphone, and 75.00% of the male students do. Overall 76.00% own one.

Example 4: income and smartphone

  1. Divide by the row totals 20, 66 and 14 (and the column-total row by 100).
  2. As percentages.
Income level \ Own a smartphoneNoYesRow total
High2/2018/2020
Medium27/6639/6666
Low9/145/1414
Column total38/10062/100100
Income level \ Own a smartphoneNoYesRow total
High10.00%90.00%20
Medium40.91%59.09%66
Low64.29%35.71%14
Column total38.00%62.00%100
Reading it

90.00% of High income participants own a smartphone, 59.09% of Medium and only 35.71% of Low.

2.2Column relative frequencies: lecture examples

Now the questions turn around: What proportion of all participants are female? and What proportion of smartphone owners are female? The second divides by the number of owners.

Example 5: gender and smartphone

  1. Divide by the column totals 24 (No) and 76 (Yes); the row-total column is divided by 100.
  2. As percentages.
Gender \ Own a smartphoneNoYesRow total
Female10/2434/7644/100
Male14/2442/7656/100
Column total2476100
Gender \ Own a smartphoneNoYesRow total
Female41.67%44.74%44.00%
Male58.33%55.26%56.00%
Column total2476100
Reading it

44.74% of the smartphone owners are female, while 44.00% of all participants are female.

Example 6: income and smartphone

  1. Divide by the column totals 38 and 62 (and the row totals by 100).
  2. As percentages.
Income level \ Own a smartphoneNoYesRow total
High2/3818/6220/100
Medium27/3839/6266/100
Low9/385/6214/100
Column total3862100
Income level \ Own a smartphoneNoYesRow total
High5.26%29.03%20.00%
Medium71.05%62.90%66.00%
Low23.68%8.06%14.00%
Column total3862100
Reading it

Among those with no smartphone, 5.26% are High income; among owners, 29.03% are High income.

Which totals sit in the marginsIn the lecture tables the margin that is not being divided keeps its raw counts: for row relative frequencies the Row total column shows 44, 56, 100, and for column relative frequencies the Column total row shows 24, 76, 100. The other margin shows the share of the grand total (for example 24.00% and 76.00%, or 44.00% and 56.00%).

2.3Going deeper

  1. Each row (or column) adds to 100%. In a row-percentage table every row sums to 100% (22.73% + 77.27%). In a column-percentage table every column does (41.67% + 58.33%). Use this as the check.
  2. Pick the denominator from the question. “Of the females, how many own one?” divides by the females (row). “Of the owners, how many are female?” divides by the owners (column). The word after “of the” tells you what to divide by.
  3. The two are not the same number. 77.27% of females own a smartphone, but 44.74% of owners are female. Mixing them up reverses the meaning.
  4. Compare with the overall split. The overall row (24.00% No, 76.00% Yes) is the baseline each group is compared against in the next chapter.
Exam tips
  • State in words what you divided by before computing.
  • Check that each row (or column) of percentages adds to 100%.
Common mistakes
  • Dividing by the grand total instead of the row or column total.
  • Using row percentages when the question is about columns.
Next · Lecture 4.3Is There an Association?
03
Lecture 4.3

Is There an Association?

Definition: associationTwo variables are associated if knowing information about one variable provides information about the other variable.

To decide whether two categorical variables are associated, we use the row relative frequencies and the column relative frequencies of the previous chapter.

Not associated: same everywhere
  • The row relative frequencies (or the column relative frequencies) are the same for all rows (columns).
Associated: different somewhere
  • The row relative frequencies (or the column relative frequencies) are different for some rows (some columns).

3.1Lecture examples

Example 7: gender and smartphone, associated?

  1. Row relative frequencies. Female: 22.73% No, 77.27% Yes. Male: 25.00% No, 75.00% Yes. The two rows are nearly identical, and both are close to the overall split of 24.00% and 76.00%.
  2. Column relative frequencies. Among non-owners 41.67% are female and 58.33% male; among owners 44.74% female and 55.26% male. These are close to the overall 44.00% and 56.00%.
  3. Conclusion. Gender and smartphone ownership are not associated: knowing a student's gender tells us almost nothing about whether the student owns a smartphone.
Close, not exactly equalThe percentages are close, not exactly equal (77.27% against 75.00%); the lecture treats them as the same and concludes there is no association.

Example 8: income and smartphone, associated?

  1. Row relative frequencies. High: 10.00% No, 90.00% Yes. Medium: 40.91% No, 59.09% Yes. Low: 64.29% No, 35.71% Yes. The rows are clearly different from one another.
  2. Column relative frequencies. Among owners 29.03% are High, 62.90% Medium and 8.06% Low; among non-owners the split is 5.26%, 71.05% and 23.68%. The columns also differ.
  3. Conclusion. Income and smartphone ownership are associated. The higher the income level, the larger the share who own a smartphone.
0%20%40%60%80%100%Female77.27%Male75%all participants: 76%0%20%40%60%80%100%Low35.71%Medium59.09%High90%all participants: 62%
Figure 2. Own a smartphone (% of the row). Left, gender: almost the same share of females and males, close to the overall 76%. Right, income: the share of owners rises sharply from Low to High, far from the overall 62%
Reading the diagrams

The dashed line is the overall share of owners. If the variables were not associated, every bar would reach about the same height, near that line (left chart, gender). In the right chart (income) the bars are far apart, so knowing the income level changes what we expect about ownership.

3.2Going deeper

  1. Two checks, one answer. Rows and columns tell the same story. If the row percentages are the same across rows, the column percentages are the same across columns too, so one of the two is enough.
  2. “Close enough” is a judgement. 77.27% against 75.00% is a gap of about 2 points, small next to the 55-point gap between High (90%) and Low (35.71%). The lecture gives no numerical cut-off; compare the size of the gaps.
  3. Association is not cause. Income and smartphone ownership go together, but the table alone does not say that income causes ownership. This remark is an extra, not from the lecture.
  4. Ordinal order helps. Because income is ordinal we can say “the higher the income, the larger the share”, a direction. For a nominal variable we can only say the groups differ.
Exam tips
  • Compare each group with the overall row.
  • Say “associated” only when some rows (or columns) clearly differ.
  • Quote two or three percentages as evidence in your conclusion.
Common mistakes
  • Comparing raw counts instead of relative frequencies.
  • Calling a 2-point difference an association.
Next · Lecture 4.3Stacked Bar Charts
04
Lecture 4.3

Stacked Bar Charts

Definition: stacked bar chartA bar chart shows the frequency of each category of one variable. A stacked bar chart (also called a segmented bar chart) represents the count for a category and, in addition, breaks each bar into smaller segments, each segment showing the frequency of a category of the second variable within that bar.

4.1Making one in Google Sheets

  1. Select the data you want to include in the contingency table.
  2. Click Insert, then Chart, and choose the stacked bar option.

4.2Lecture examples

Example 9: gender and smartphone

Draw the stacked bar chart and the 100% stacked bar chart for the gender and smartphone data.

  1. Stacked bars of counts. One bar per gender. The bar height is the number of students (44 and 56); it is split into No (10, 14) and Yes (34, 42).
  2. 100% stacked bars. Rescale every bar to the same height, 100%, so each segment is the row percentage from the table.
02040601034Female1442MaleYesNoGenderCount0%25%50%75%100%22.73%77.27%Female25.00%75.00%MaleYesNoGenderPercent
Figure 3. Gender versus smartphone ownership. Left: stacked bars of counts. Right: 100% stacked bars, the row percentages
  • Read the chart. The Yes segment is almost the same fraction of both 100% bars, which matches the earlier conclusion that gender and ownership are not associated.

Example 10: income and smartphone

Draw the stacked bar chart and the 100% stacked bar chart for the income and smartphone data.

  1. Stacked bars of counts. One bar per income level (14, 66, 20 participants), split into No and Yes.
  2. 100% stacked bars. Each bar rescaled to 100%.
02040608095Low2739Medium218HighYesNoIncome levelCount0%25%50%75%100%64.29%35.71%Low40.91%59.09%Medium10.00%90.00%HighYesNoIncome levelPercent
Figure 4. Income versus smartphone ownership. Left: stacked bars of counts. Right: 100% stacked bars
  • Read the chart. The Yes segment grows from 35.71% (Low) to 59.09% (Medium) to 90.00% (High), so the bars differ: income and ownership are associated.
A note on the lecture's chartsThe lecture's charts label the income levels 1, 2 and 3; from the bar heights these are Low, Medium and High in that order, so the bars here follow the same order, which keeps the ordinal order of the variable.
Reading the diagrams

A 100% stacked bar chart is useful for part-to-whole relationships: every bar has the same height, so only the split can differ. Equal splits mean no association; changing splits mean association. The ordinary stacked chart shows the sizes of the groups as well, which the 100% chart hides.

4.3Going deeper: which chart to use

Stacked bars (counts)100% stacked bars
Bar heightNumber of cases in the groupAlways 100%
SegmentsCountsRow percentages
Shows group sizesYesNo
Best forSeeing how big each group isComparing the splits to judge association
Exam tips
  • Use the 100% chart when the question is about association.
  • Keep the segments in the same order and colour in every bar.
Common mistakes
  • Comparing segment heights across bars of different sizes in the count chart.
  • Forgetting the legend that says which colour is Yes.
Next · Lecture 4.4Scatter Plots
05
Lecture 4.4

Scatter Plots

Definition: scatter plotA scatter plot is a graph that displays pairs of values as points on a two-dimensional plane. We use it to look for association between two numerical variables.

5.1Which variable goes on which axis

x-axis: explanatory variable
  • The variable which explains: it goes on the horizontal axis.
y-axis: response variable
  • The variable you would like to explain: it goes on the vertical axis.

5.2Lecture examples

Example 11: age and height of children

The ages and heights of five children are given. Draw the scatter plot.

Age (years)12345
Height (cm)758594101108
  1. Age explains height, so age is the explanatory variable (x) and height the response variable (y).
  2. Plot the five points (1, 75), (2, 85), (3, 94), (4, 101), (5, 108).
  3. The points rise from left to right: taller heights go with greater ages.
607080901001101200123456Age (years)Height (cm)
Figure 5. Scatter plot of height against age

Example 12: prices of homes

A real estate agent collected the prices of different sizes of homes. He wanted to see the relationship between the price of a home and its size; in particular, whether prices increase linearly with size or in some other way. He collected data on 15 homes: the size in 1000 square feet and the price in lakhs of rupees.

HomeSize (1000 sq ft)Price (INR lakhs)
10.868
2181
31.172
41.391
51.687
61.856
72.383
82.3112
HomeSize (1000 sq ft)Price (INR lakhs)
92.593
102.598
112.7136
123.1109
133.1122
143.2159
153.4170
  1. Size is the explanatory variable (x) and price the response variable (y).
  2. Plot the 15 pairs. Two homes of size 2.3 have prices 83 and 112, and two of size 2.5 have prices 93 and 98.
  3. The cloud climbs from lower left to upper right, so larger homes tend to cost more. The points are scattered around the climb, not exactly on a line.
0501001502000.511.522.533.5Size (1000 square feet)Price (INR lakhs)
Figure 6. Scatter plot of the price of 15 homes against their size

5.3The visual test for association

Visual testDo we see a pattern in the scatter plot? In other words: if I know the x-value, can I use it to say something about the y-value, or to guess it? If yes, the variables are associated.

5.4Scatter plot in Google Sheets

  1. Highlight the data you want to plot.
  2. Click Insert, then Chart, and choose the scatter chart.
  3. Under the X-axis tab, choose your explanatory variable.
  4. Under the Series tab, choose the response variable.
  5. Label the title of the chart and the axes appropriately.

5.5Going deeper

  1. Which variable is x? Ask: which one would I use to explain or predict the other? Age explains height; size explains price. Swapping them gives a different picture.
  2. Each point is one case. Home 7 is the point (2.3, 83); home 8 is (2.3, 112). Two points can share an x-value.
  3. Pattern, not exactness. The homes rise with size but do not lie on a line: the price also depends on other things. Chapters 6 to 9 give ways to describe and measure that.
  4. Axes need not start at zero. The home plot starts at 0.5 on x so the points fill the picture; check the axis labels before reading.
Exam tips
  • Write “x = ..., y = ...” before plotting.
  • Label both axes with the variable and its unit.
Common mistakes
  • Putting the response variable on the x-axis.
  • Joining the points with lines (a scatter plot shows points only).
Next · Lecture 4.5Describing Association
06
Lecture 4.5

Describing Association

When describing the association between two variables in a scatter plot, four key questions need to be answered:

1. Direction
  • Does the pattern trend up, down, or both?
2. Curvature
  • Does the pattern appear to be linear or does it curve?
3. Variation
  • Are the points tightly clustered along the pattern?
4. Outliers
  • Did you find something unexpected?
SourceThe four questions come from Stine and Foster, Statistics for Business: Decision Making and Analysis (Addison-Wesley, 2011), as cited on the slide.

6.1Direction

An upward pattern means larger values of x go with larger values of y; a downward pattern means larger values of x go with smaller values of y.

60801001200123456Age (years)Height (cm)024680123456Age (years)Price (INR lakhs)
Figure 7. Upward and downward patterns, drawn from the age and height data (left) and the age and price of a car data (right) used in the covariance examples

6.2Curvature

Look at whether the points follow a straight line or bend. The lecture shows four plots: linear patterns trending up and down, and two that curve, one bending upward and one levelling off.

xyxyxyxy
Figure 8. Illustrative sketches (not the lecture's data) of the four shapes in the curvature slide: linear up, linear down, curves upward (steeper and steeper), curves downward (levels off)

6.3Variation

xyxy
Figure 9. Illustrative sketches: the same upward pattern with little scatter (left) and a lot of scatter (right)

6.4Outliers

outlieroutlierxy
Figure 10. Illustrative sketch: a clear pattern with two points that do not follow it
Reading the diagrams

Answer the four questions in order. Direction: which way does the pattern go? Curvature: does a straight line describe it, or does it bend? Variation: how tightly do the points hug the pattern? Outliers: is any point far from the rest? A good description of a scatter plot mentions all four.

A note on the sketchesThe lecture's own plots for this section come from the housing data and a separate data set of car prices whose values are not listed on the slides, so the curvature, variation and outlier sketches above are illustrations of the four ideas, not the lecture's data.

6.5Going deeper: a sample description

For the 15 homes (Chapter 5): Direction: upward, larger homes tend to cost more. Curvature: roughly linear. Variation: moderate, the points are scattered around the climb. Outliers: none stands far from the cloud. (This is a reading of the plot, not a number from the lecture.)

Exam tips
  • Use the four words in the answer: direction, curvature, variation, outliers.
  • Say “linear” only if a straight line fits the cloud.
Common mistakes
  • Ignoring an outlier because it spoils the pattern.
  • Calling a curved pattern linear.
Next · Lecture 4.6Covariance
07
Lecture 4.6

Covariance

How do we measure the strength of the association between two variables? The lecture introduces two measures: covariance and correlation.

Idea: covariance

Covariance quantifies the strength of the linear association between two numerical variables.

7.1Deviations from the means

The lecture builds covariance from two columns of deviations: xi−xˉx_i - \bar{x} and yi−yˉy_i - \bar{y}.

Example 13: age and height, the deviations

Age x (years)12345
Height y (cm)758594101108
  1. Means. xˉ=1+2+3+4+55=3\bar{x} = \frac{1+2+3+4+5}{5} = 3 and yˉ=75+85+94+101+1085=4635=92.6\bar{y} = \frac{75+85+94+101+108}{5} = \frac{463}{5} = 92.6.
  2. Deviations. Subtract the means:
XYX − X̄Y − Ȳ
175-2-17.6
285-1-7.6
39401.4
410118.4
5108215.4

Example 14: age and price of a car, the deviations

Age x (years)12345
Price y (INR lakhs)65432
  1. Means. xˉ=3\bar{x} = 3 and yˉ=6+5+4+3+25=4\bar{y} = \frac{6+5+4+3+2}{5} = 4.
  2. Deviations.
XYX − X̄Y − Ȳ
16-22
25-11
3400
431-1
522-2
A discrepancy in the slideThe slide that first fills in these deviations prints -1 for the last y deviation (price 2); the correct value is 2 - 4 = -2, and the following slide prints -2.

7.2Multiplying the deviations

Example 15: age and height, products of deviations

Step 3. Multiply (xi−xˉ)(yi−yˉ)(x_i - \bar{x})(y_i - \bar{y}) for each person and add the products.

XYX − X̄Y − Ȳ(X − X̄)(Y − Ȳ)
175-2-17.635.2
285-1-7.67.6
39401.40
410118.48.4
5108215.430.8
Sum82

Every product is zero or positive: when age is above average so is height, and when age is below average so is height.

607080901001101200123456mean of x = 3mean of y = 92.6Age (years)Height (cm)0123456701234567mean of x = 3mean of y = 4Age (years)Price (INR lakhs)
Figure 11. The dashed lines are the two means. Green points lie in the quadrants where the two deviations have the same sign, red points where the signs differ; a grey point sits on a mean line. Left: age and height. Right: age and price of a car, where every point is red or on the line

Example 16: age and price of a car, products of deviations

XYX − X̄Y − Ȳ(X − X̄)(Y − Ȳ)
16-22-4
25-11-1
34000
431-1-1
522-2-4
Sum-10

Every product is zero or negative: when age is above average the price is below average, and the other way round.

Same signs: large with large, small with small
  • When large (small) values of x tend to go with large (small) values of y, the signs of the deviations xi−xˉx_i - \bar{x} and yi−yˉy_i - \bar{y} tend to be the same.
Different signs: large with small
  • When large (small) values of x tend to go with small (large) values of y, the signs of the deviations tend to be different.
Reading the diagrams

The dashed lines are the two means and cut the plane into four quadrants. A point to the right of the vertical line has a positive x deviation, a point above the horizontal line a positive y deviation. In the green quadrants the two signs agree, so the product is positive; in the red quadrants they disagree, so it is negative. Adding the products therefore adds up how many points (and how far) lie in each kind of quadrant.

7.3Definition of covariance

Definition: covarianceLet xix_i be the ith observation of variable x and yiy_i the ith observation of variable y, so (xi,yi)(x_i, y_i) is the ith paired observation of a population (sample) data set with NN (nn) observations. The covariance between x and y is:
Population covariance (N observations)
Cov(x,y)=∑i=1N(xi−xˉ)(yi−yˉ)N\text{Cov}(x,y) = \frac{\sum_{i=1}^{N}(x_i - \bar{x})(y_i - \bar{y})}{N}
Sample covariance (n observations)
Cov(x,y)=∑i=1n(xi−xˉ)(yi−yˉ)n−1\text{Cov}(x,y) = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{n-1}

Example 17: covariance of age and height

  1. From Section 7.2 the sum of the products is 82.
  2. There are 5 observations.
Population covariance=825=16.4Sample covariance=824=20.5\text{Population covariance} = \frac{82}{5} = 16.4 \qquad \text{Sample covariance} = \frac{82}{4} = 20.5

Example 18: covariance of age and price of a car

  1. The sum of the products is -10.
  2. There are 5 observations.
Population covariance=−105=−2Sample covariance=−104=−2.5\text{Population covariance} = \frac{-10}{5} = -2 \qquad \text{Sample covariance} = \frac{-10}{4} = -2.5
Units of covarianceThe size of the covariance is difficult to interpret because the covariance has units: the units of x times the units of y. For age (years) and height (cm), the covariance 20.5 is in year-cm; for age and price it is in year-lakh. This is why the next chapter divides by the standard deviations.

7.4Going deeper

  1. The sign tells the direction. Positive covariance (16.4, 20.5): upward pattern. Negative (-2, -2.5): downward pattern. Near zero: no linear pattern.
  2. The size depends on units. Measuring height in metres instead of cm would divide the covariance by 100 without changing the pattern. So 20.5 versus -2.5 cannot be compared directly. This is an extra remark that follows from the definition.
  3. Same recipe as variance. The variance divides ∑(xi−xˉ)2\sum (x_i - \bar{x})^2 by n−1n-1; the covariance replaces one of the squares by the other variable's deviation. So the covariance of x with itself is its variance (extra remark).
  4. Population or sample? Use NN for the whole population and n−1n - 1 for a sample, as for the variance.
Exam tips
  • Build the table: x, y, deviations, products; then add the products.
  • Check that each deviation column adds to 0.
  • Keep the sign of the sum: it is the direction.
Common mistakes
  • Subtracting the mean after multiplying.
  • Dividing a sample covariance by n instead of n - 1.
  • Quoting a covariance without saying it has units.
Next · Lecture 4.7Correlation
08
Lecture 4.7

Correlation

A more easily interpreted measure of linear association between two numerical variables is correlation. It is derived from covariance.

Definition: Pearson correlation coefficientTo find the correlation between x and y, divide the covariance between x and y by the product of the standard deviations of x and y. The Pearson correlation coefficient rr is
r=cov(x,y)sx sy=∑i=1n(xi−xˉ)(yi−yˉ)∑i=1n(xi−xˉ)2 ∑i=1n(yi−yˉ)2r = \frac{\text{cov}(x,y)}{s_x\, s_y} = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i - \bar{x})^2}\ \sqrt{\sum_{i=1}^{n}(y_i - \bar{y})^2}}
Remark 1: units cancel
  • The units of the standard deviations cancel out the units of the covariance, so rr has no units.
Remark 2: always between -1 and +1
  • It can be shown that the correlation always lies between −1-1 and +1+1.

8.1Lecture examples

Example 19: correlation of age and height

  1. Square the deviations and add them:
XYX − X̄Y − Ȳ(X − X̄)²(Y − Ȳ)²(X − X̄)(Y − Ȳ)
175-2-17.64309.7635.2
285-1-7.6157.767.6
39401.401.960
410118.4170.568.4
5108215.44237.1630.8
Sum10677.282
  1. Standard deviations. sx=104=1.58s_x = \sqrt{\frac{10}{4}} = 1.58 and sy=677.24=13.01s_y = \sqrt{\frac{677.2}{4}} = 13.01.
  2. Correlation.
r=8210×677.2or20.51.58×13.01=0.9964r = \frac{82}{\sqrt{10 \times 677.2}} \quad\text{or}\quad \frac{20.5}{1.58 \times 13.01} = 0.9964
Keep full precisionDividing 82 by the square root of 6772 gives 0.99645, which the slide shows as 0.9964. If you use the rounded values 1.58 and 13.01 in the second form you get 0.9973, so keep full precision for the standard deviations and round only at the end.

Example 20: correlation of age and price of a car

  1. Square the deviations and add them:
XYX − X̄Y − Ȳ(X − X̄)²(Y − Ȳ)²(X − X̄)(Y − Ȳ)
16-2244-4
25-1111-1
3400000
431-111-1
522-244-4
Sum1010-10
  1. Standard deviations. sx=sy=104=1.58s_x = s_y = \sqrt{\frac{10}{4}} = 1.58.
  2. Correlation.
r=−1010×10=−1or−2.51.58×1.58≈−1r = \frac{-10}{\sqrt{10 \times 10}} = -1 \quad\text{or}\quad \frac{-2.5}{1.58 \times 1.58} \approx -1
RoundingWith the rounded 1.58 the second form gives -1.0016; the exact value is -1. A correlation can never go beyond -1 or +1, so this small excess is only rounding.
-1-0.500.5+1large with smalllarge with largeAge and height r = 0.9964Age and price of a car r = -1
Figure 12. The two correlations of this chapter on the scale from -1 to +1
Reading the diagram

The green half of the scale is positive correlation (large with large) and the red half is negative correlation (large with small). Age and height give 0.9964, almost +1: very strong upward linear association. Age and the price of a car give exactly -1: a perfect downward line, since the five points lie exactly on a straight line going down.

8.2Correlation in Google Sheets

The function CORREL(series1, series2) returns the value of the correlation. If the x-variable (series1) is in cells A2:A6 and the y-variable (series2) in cells B2:B6, then CORREL(A2:A6,B2:B6) returns the Pearson correlation coefficient.

8.3Going deeper: how to read r

Value of rMeaning
+1perfect upward line
close to +1 (0.9964)very strong upward linear association
0no linear association
close to -1strong downward linear association
-1perfect downward line (age and price of the 5 cars)
  1. Sign and size. The sign gives the direction; the distance from 0 gives the strength of the linear association.
  2. Only linear. A curved pattern can have rr near 0 and still be a strong association. That is why Chapter 6 asks about curvature before computing anything.
  3. Units do not matter. Because rr has no units, measuring height in metres or in cm gives the same rr (extra remark).
  4. Order does not matter. The formula is symmetric in x and y, so rr is the same if you swap them (extra remark).
  5. Never beyond ±1\pm 1. If you get 1.0016 or -1.2, there is a calculation or rounding mistake.
Exam tips
  • Compute the sum of products and the two sums of squares; then r=Sxy/SxxSyyr = S_{xy} / \sqrt{S_{xx} S_{yy}}.
  • Round only at the very end.
Common mistakes
  • Rounding the standard deviations first (0.9973 instead of 0.9964).
  • Reading r = 0 as “no association at all”.
Next · Lectures 4.7 and 4.8Fitting a Line
09
Lectures 4.7 and 4.8

Fitting a Line

The strength of linear association was measured with covariance and correlation. The linear association can also be described with the equation of a line. This chapter summarises a scatter plot with a line and introduces R2R^2.

9.1Equation of the line in Google Sheets

  1. Open the scatter plot.
  2. Under the Customize tab, click on Series.
  3. Click on Trendline.
  4. Under the Label tab, choose Use equation and click the Show R² button.

9.2Lecture examples

Example 21: size versus price of homes

For the 15 homes of Chapter 5, find the equation of the line, R2R^2 and rr.

  1. Fit. Put size on the x-axis, price on the y-axis, and add the trendline with its equation and R2R^2.
  2. Reading the line. The slope 30.5 says that the line rises by 30.5 lakh for every extra 1000 square feet.
  3. Check. 0.646=0.804\sqrt{0.646} = 0.804 and 0.8042≈0.647=R20.804^2 \approx 0.647 = R^2.
Price=30.5×Size+36,R2=0.647,r=0.804\text{Price} = 30.5 \times \text{Size} + 36, \qquad R^2 = 0.647, \qquad r = 0.804
0501001502000.511.522.533.5Price = 30.5 × Size + 36; R² = 0.647Size (1000 square feet)Price (INR lakhs)
Figure 13. The 15 homes with the fitted line Price = 30.5 × Size + 36
Recomputed from the 15 data pointsRecomputing from the 15 data points confirms the slide: slope 30.48, intercept 36.02, r=0.8045r = 0.8045 and R2=0.6472R^2 = 0.6472. The slide prints r=0.804r = 0.804; rounded to three places the exact value would be 0.805 (0.804 is the square root of the rounded R2R^2).

Example 22: age versus price of cars

For a data set of the age and price of cars, find the equation of the line, R2R^2 and rr.

  1. Fit the trendline in the scatter plot of price against age.
  2. Reading the line. The slope is negative: the line falls by 0.694 lakh for each extra year of age. The points lie close to the line.
  3. Check. (−0.9247)2=0.855=R2(-0.9247)^2 = 0.855 = R^2.
Price=−0.694×Age+9.03,R2=0.855,r=−0.9247\text{Price} = -0.694 \times \text{Age} + 9.03, \qquad R^2 = 0.855, \qquad r = -0.9247
Data not listedThe slide plots about a dozen cars whose values are not listed, so only the equation, R2R^2 and rr can be reproduced here. This is a different data set from the five cars of Chapter 7.

Example 23: size versus price of homes, a weak line

For a second data set of the size and price of homes, find the equation of the line, R2R^2 and rr.

  1. Fit the trendline.
  2. Reading the line. The line is almost flat (a slope of only 7.77) and the points are scattered widely around it.
  3. Check. 0.022≈0.149=r\sqrt{0.022} \approx 0.149 = r.
Price=7.77×Size+130,R2=0.022,r=0.149\text{Price} = 7.77 \times \text{Size} + 130, \qquad R^2 = 0.022, \qquad r = 0.149
Data not listedThe values of this second housing data set are not listed on the slides; only its equation, R2R^2 and rr are given.

9.3All the lines side by side

ExampleEquation of the lineR²rTightness of points
Size and price (15 homes)Price = 30.5 × Size + 360.6470.804moderately close
Age and price of carsPrice = −0.694 × Age + 9.030.855−0.9247close to the line
Size and price (second set)Price = 7.77 × Size + 1300.0220.149widely scattered
-1-0.500.5+1large with smalllarge with largeAge and price (5 cars) r = -1Age and price of cars r = -0.9247Size and price (second set) r = 0.149Size and price (15 homes) r = 0.804Age and height r = 0.9964
Figure 14. Every correlation in the lectures on one scale: values near ±1 are strong linear association, values near 0 are weak
Reading the table and diagram

The sign of rr matches the sign of the slope (positive 30.5 with +0.804, negative -0.694 with -0.9247, positive 7.77 with +0.149). The closer rr is to ±1, the larger R2R^2 and the more tightly the points hug the line; with r=0.149r = 0.149 the line explains almost nothing and R2R^2 is 0.022.

9.4Going deeper

  1. Slope and intercept. In Price = 30.5 × Size + 36 the slope 30.5 is the change in price for one more unit of size; the intercept 36 is the line's value at size 0 (here just where the line starts, not a real home).
  2. R2=r2R^2 = r^2. For a fitted straight line, R2R^2 is the square of rr, which is the check used in every example. So R2R^2 is between 0 and 1, and the sign of rr comes from the slope.
  3. What R2R^2 says. 0.647 means roughly 65% of the ups and downs in price go along with size, and 0.022 means almost none do. This reading is the usual one, an extra to the lecture, which only says R2R^2 goes with the line.
  4. Do not predict far outside the data. The homes in the data are 0.8 to 3.4 thousand square feet; the line says little about a 10 000 square foot home (extra remark).
Exam tips
  • Check: r2r^2 should equal R2R^2, and the sign of rr should match the slope.
  • Say the slope with units: lakh per 1000 square feet.
Common mistakes
  • Reading the slope as the correlation (30.5 is not r).
  • Giving r a positive sign when the slope is negative.
Next · Lecture 4.9Categorical and Numerical Variables
10
Lecture 4.9

Categorical and Numerical Variables

The last lecture asks how a categorical variable is associated with a numerical variable, when the categorical variable has just two categories (it is dichotomous).

10.1Lecture example: gender versus marks

Example 24: gender versus marks

A teacher wants to know whether female students performed better than male students in her class. She collected the marks (out of 100) of twenty students in the subject.

#GenderMarks
1F71
2F67
3F65
4M69
5M75
6M83
7F91
8F85
9F69
10F75
#GenderMarks
11M92
12F79
13M71
14M94
15F86
16F75
17F90
18M84
19F91
20M90
  1. Code the categorical variable as 0 and 1. The lecture's scatter plot puts the females at 0 and the males at 1 (the marks at 0 range from 65 to 91, the marks at 1 from 69 to 94).
  2. Plot marks (numerical) against the gender code.
60708090100-0.500.511.5Gender code (0 = F, 1 = M)Marks
Figure 15. The marks of the 20 students plotted against the gender code (points with equal marks sit on top of each other)
  1. Group the same marks by gender to compare them.
6065707580859095100Female (n = 12)mean 78.67Male (n = 8)mean 82.25
Figure 16. The marks split by gender, with each group mean marked

Female marks: 12 values, sum 944, so the mean is 944/12=78.67944/12 = 78.67. Male marks: 8 values, sum 658, mean 658/8=82.25658/8 = 82.25.

Reading the diagrams

The two vertical stripes of the coded plot overlap heavily: both groups reach from the late sixties to the nineties. In the grouped picture the two means (78.67 and 82.25) are only a few marks apart compared with the spread inside each group. So gender separates the marks only slightly.

10.2Point bi-serial correlation coefficient

Let XX be a numerical variable and YY a categorical variable with two categories (a dichotomous variable). To calculate the point bi-serial correlation between them:

  1. Group the data into two sets based on the value of the dichotomous variable YY; assume the value of YY is either 0 or 1.
  2. Means. Calculate the mean values of the two groups: Yˉ0\bar{Y}_0 and Yˉ1\bar{Y}_1 for the groups with Y=0Y = 0 and Y=1Y = 1.
  3. Proportions and spread. Let p0p_0 and p1p_1 be the proportions of observations with Y=0Y = 0 and Y=1Y = 1, and sXs_X the standard deviation of the numerical variable XX.
rpb=Yˉ0−Yˉ1sX p0 p1r_{pb} = \frac{\bar{Y}_0 - \bar{Y}_1}{s_X}\,\sqrt{p_0\, p_1}
A note on the notationThe slide introduces XX as the numerical variable and YY as the categorical one but then writes the group means as Yˉ0\bar{Y}_0 and Yˉ1\bar{Y}_1; they are the means of the numerical variable (here marks) within the two categories.

Example 25: point bi-serial correlation of gender and marks

  1. Groups. Y=0Y = 0 for the 12 females and Y=1Y = 1 for the 8 males (as in the lecture's plot).
  2. Group means. Yˉ0=94412=78.67\bar{Y}_0 = \frac{944}{12} = 78.67 and Yˉ1=6588=82.25\bar{Y}_1 = \frac{658}{8} = 82.25.
  3. Proportions. p0=1220=0.6p_0 = \frac{12}{20} = 0.6 and p1=820=0.4p_1 = \frac{8}{20} = 0.4, so p0p1=0.24=0.490\sqrt{p_0 p_1} = \sqrt{0.24} = 0.490.
  4. Standard deviation of all 20 marks. The marks add up to 1602, so the mean is 80.1, and the sample standard deviation is 9.57.
  5. Substitute.
rpb=78.67−82.259.57×0.490≈−0.18r_{pb} = \frac{78.67 - 82.25}{9.57} \times 0.490 \approx -0.18
  • Using the population standard deviation (9.33, dividing by 20) instead gives -0.19; either way the size is about 0.18 to 0.19.
  • Interpret. The size 0.18 is small, so the association between gender and marks in this class is weak. The negative sign only reflects the coding: the group coded 1 (males) has the higher mean. Swapping the codes would flip the sign and leave the size unchanged.
A note on this solutionThe lecture states the formula but does not show a worked calculation, so this solution is worked out from the printed formula. The slide does not say which standard deviation to use or which gender is coded 0, so those two choices are a reading of the earlier lectures and the plot. A second scatter plot on the slides (titled “Gender-coded and Marks-2”) shows a different data set in which the two groups are clearly separated; its values are not listed.

10.3Going deeper

  1. The formula in words. rpbr_{pb} is the gap between the two group means, measured in standard deviations of all the marks, and then shrunk by p0p1\sqrt{p_0 p_1}. A big gap compared with the spread gives a big ∣rpb∣|r_{pb}|.
  2. Which group is 0 is your choice. The sign changes, the size does not. Always say which group is coded 1 when you state the sign.
  3. It is a Pearson correlation. With a 0/1 variable, the ordinary correlation formula of Chapter 8 gives the same number (extra remark; the lecture gives only the formula above).
  4. Compare means first. The quickest check is the two group means: 78.67 against 82.25, only about 3.6 marks apart.
Exam tips
  • State the coding (which group is 0 and which is 1).
  • Use the same standard deviation (sample or population) throughout, and say which.
Common mistakes
  • Using the standard deviation of one group instead of all the marks.
  • Reading the negative sign as “females do worse”.
Next · All lecturesWeek 4 Summary Sheet
11
All lectures

Week 4 Summary Sheet

Everything in Week 4 on one sheet, for a last-minute revision.

Which tool for which pair of variables

VariablesSummary tableGraphMeasure of association
Two categoricalContingency table; row and column relative frequenciesStacked and 100% stacked bar chartSame relative frequencies in all rows (columns): no association
Two numerical-Scatter plot (x explanatory, y response)Covariance, correlation r, fitted line and R²
Categorical (2 categories) and numericalGroup means of the two categoriesScatter plot against a 0 / 1 codePoint bi-serial correlation r_pb

Formulas

Relative frequencies
cellrow totalorcellcolumn total\frac{\text{cell}}{\text{row total}} \quad\text{or}\quad \frac{\text{cell}}{\text{column total}}
Covariance
∑(xi−xˉ)(yi−yˉ)Nor∑(xi−xˉ)(yi−yˉ)n−1\frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{N} \quad\text{or}\quad \frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{n-1}
Correlation
r=cov(x,y)sx sy,−1≤r≤1r = \frac{\text{cov}(x,y)}{s_x\, s_y}, \qquad -1 \le r \le 1
Point bi-serial
rpb=Yˉ0−Yˉ1sXp0 p1r_{pb} = \frac{\bar{Y}_0 - \bar{Y}_1}{s_X}\sqrt{p_0\, p_1}

Google Sheets steps

TaskHow
Contingency tableData → Pivot table; variables in Rows and Columns; Values with COUNTA
Stacked bar chartSelect the table; Insert → Chart → stacked bar
Scatter plotInsert → Chart → scatter; x = explanatory, series = response
CorrelationCORREL(series1, series2)
Equation of the line and R²Customize → Series → Trendline → Use equation, Show R²

Values computed in the lectures

ExampleResult
Gender and smartphone: row percentagesFemale 22.73% / 77.27%; Male 25.00% / 75.00% (not associated)
Income and smartphone: row percentagesHigh 10.00% / 90.00%; Medium 40.91% / 59.09%; Low 64.29% / 35.71% (associated)
Age and heightSum of products 82; covariance 16.4 (population), 20.5 (sample); r = 0.9964
Age and price of a carSum of products -10; covariance -2 (population), -2.5 (sample); r = -1
Size and price of homesPrice = 30.5 × Size + 36; R² = 0.647; r = 0.804
Age and price of cars (second set)Price = −0.694 × Age + 9.03; R² = 0.855; r = −0.9247
Size and price (weak set)Price = 7.77 × Size + 130; R² = 0.022; r = 0.149
Gender and marksmeans 78.67 and 82.25; r_pb ≈ -0.18

Topic by topic

Two categorical variables
  • Contingency table; keep ordinal order.
  • Row and column relative frequencies.
  • Same percentages: no association.
  • Stacked and 100% stacked bars.
Scatter plot
  • x explanatory, y response.
  • Direction, curvature, variation, outliers.
Covariance and correlation
  • Cov: mean of (x - x̄)(y - ȳ); N or n - 1; has units.
  • r = cov / (sx sy), between -1 and +1, no units.
Fitted line and mixed data
  • Sheets trendline: equation and R².
  • Slope sign matches the sign of r.
  • Two-category variable: code 0/1, group means, r_pb.
Revision overview
Two categorical variablesContingency table (pivot table, COUNTA)
Row and column relative frequencies
Same row (column) percentages: no association
Stacked and 100% stacked bar charts
Scatter plotx = explanatory, y = response
Describe: direction, curvature, variation, outliers
CovarianceMean of (x - x bar)(y - y bar)
Population: divide by N; sample: divide by n - 1
Has units: units of x times units of y
Association between variablesStatistics for Data Science 1
Correlation rr = cov(x, y) / (sx sy)
Always between -1 and +1
CORREL(series1, series2)
Fitted lineSheets trendline: equation and R squared
Slope sign matches the sign of r
Categorical and numericalGroup the numbers by the two categories
Point bi-serial correlation r_pb
Revision: the whole of Week 4 on one map
Back to top