{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "path_data = '../../data/'\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import math\n",
    "from scipy import stats\n",
    "\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "plt.style.use('fivethirtyeight')\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "def r_scatter(r):\n",
    "    plt.figure(figsize=(5,5))\n",
    "    \"Generate a scatter plot with a correlation approximately r\"\n",
    "    x = np.random.normal(0, 1, 1000)\n",
    "    z = np.random.normal(0, 1, 1000)\n",
    "    y = r*x + (np.sqrt(1-r**2))*z\n",
    "    plt.scatter(x, y)\n",
    "    plt.xlim(-4, 4)\n",
    "    plt.ylim(-4, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Correlation\n",
    "\n",
    "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*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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](http://www.stat.ufl.edu/%7Ewinner/) of the University of Florida. The columns:\n",
    "\n",
    "- `vehicle`: model of the car\n",
    "- `year`: year of manufacture\n",
    "- `msrp`: manufacturer's suggested retail price in 2013 dollars\n",
    "- `acceleration`: acceleration rate in km per hour per second\n",
    "- `mpg`: fuel econonmy in miles per gallon\n",
    "- `class`: the model's class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "hybrid = pd.read_csv(path_data + 'hybrid.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>vehicle</th>\n",
       "      <th>year</th>\n",
       "      <th>msrp</th>\n",
       "      <th>acceleration</th>\n",
       "      <th>mpg</th>\n",
       "      <th>class</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Prius (1st Gen)</td>\n",
       "      <td>1997</td>\n",
       "      <td>24509.74</td>\n",
       "      <td>7.46</td>\n",
       "      <td>41.26</td>\n",
       "      <td>Compact</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Tino</td>\n",
       "      <td>2000</td>\n",
       "      <td>35354.97</td>\n",
       "      <td>8.20</td>\n",
       "      <td>54.10</td>\n",
       "      <td>Compact</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Prius (2nd Gen)</td>\n",
       "      <td>2000</td>\n",
       "      <td>26832.25</td>\n",
       "      <td>7.97</td>\n",
       "      <td>45.23</td>\n",
       "      <td>Compact</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Insight</td>\n",
       "      <td>2000</td>\n",
       "      <td>18936.41</td>\n",
       "      <td>9.52</td>\n",
       "      <td>53.00</td>\n",
       "      <td>Two Seater</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Civic (1st Gen)</td>\n",
       "      <td>2001</td>\n",
       "      <td>25833.38</td>\n",
       "      <td>7.04</td>\n",
       "      <td>47.04</td>\n",
       "      <td>Compact</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>148</th>\n",
       "      <td>S400</td>\n",
       "      <td>2013</td>\n",
       "      <td>92350.00</td>\n",
       "      <td>13.89</td>\n",
       "      <td>21.00</td>\n",
       "      <td>Large</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>149</th>\n",
       "      <td>Prius Plug-in</td>\n",
       "      <td>2013</td>\n",
       "      <td>32000.00</td>\n",
       "      <td>9.17</td>\n",
       "      <td>50.00</td>\n",
       "      <td>Midsize</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>150</th>\n",
       "      <td>C-Max Energi Plug-in</td>\n",
       "      <td>2013</td>\n",
       "      <td>32950.00</td>\n",
       "      <td>11.76</td>\n",
       "      <td>43.00</td>\n",
       "      <td>Midsize</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>151</th>\n",
       "      <td>Fusion Energi Plug-in</td>\n",
       "      <td>2013</td>\n",
       "      <td>38700.00</td>\n",
       "      <td>11.76</td>\n",
       "      <td>43.00</td>\n",
       "      <td>Midsize</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>152</th>\n",
       "      <td>Chevrolet Volt</td>\n",
       "      <td>2013</td>\n",
       "      <td>39145.00</td>\n",
       "      <td>11.11</td>\n",
       "      <td>37.00</td>\n",
       "      <td>Compact</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>153 rows × 6 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                   vehicle  year      msrp  acceleration    mpg       class\n",
       "0          Prius (1st Gen)  1997  24509.74          7.46  41.26     Compact\n",
       "1                     Tino  2000  35354.97          8.20  54.10     Compact\n",
       "2          Prius (2nd Gen)  2000  26832.25          7.97  45.23     Compact\n",
       "3                  Insight  2000  18936.41          9.52  53.00  Two Seater\n",
       "4          Civic (1st Gen)  2001  25833.38          7.04  47.04     Compact\n",
       "..                     ...   ...       ...           ...    ...         ...\n",
       "148                   S400  2013  92350.00         13.89  21.00       Large\n",
       "149          Prius Plug-in  2013  32000.00          9.17  50.00     Midsize\n",
       "150   C-Max Energi Plug-in  2013  32950.00         11.76  43.00     Midsize\n",
       "151  Fusion Energi Plug-in  2013  38700.00         11.76  43.00     Midsize\n",
       "152         Chevrolet Volt  2013  39145.00         11.11  37.00     Compact\n",
       "\n",
       "[153 rows x 6 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hybrid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 24000 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "hybrid.plot.scatter('acceleration', 'msrp')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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. \n",
    "\n",
    "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. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 21648 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "hybrid.plot.scatter('mpg', 'msrp')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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. \n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 16620 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "suv = hybrid[hybrid['class'] == 'SUV']\n",
    "suv.plot.scatter('mpg', 'msrp')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 17596 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "suv.plot.scatter('acceleration', 'msrp')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "Recall that in an earlier section we defined the function `standard_units` to convert an array of numbers to standard units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def standard_units(any_numbers):\n",
    "    \"Convert any array of numbers to standard units.\"\n",
    "    return (any_numbers - np.mean(any_numbers))/np.std(any_numbers)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can use this function to re-draw the two scatter diagrams for SUVs, with all the variables measured in standard units.  \n",
    "\n",
    "(*employing Pandas plotting function instead of matplotlib*)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 18028 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "SUVs = pd.DataFrame(\n",
    "    {'mpg (standard units)':standard_units(suv['mpg']), \n",
    "    'msrp (standard units)':standard_units(suv['msrp'])}\n",
    ").plot.scatter(0, 1)\n",
    "\n",
    "plt.xlim(-3, 3)\n",
    "\n",
    "plt.ylim(-3, 3)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 19064 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "pd.DataFrame(\n",
    "    {'acceleration (standard units)':standard_units(suv['acceleration']), \n",
    "    'msrp (standard units)':standard_units(suv['msrp'])}).plot.scatter(0, 1)\n",
    "\n",
    "plt.xlim(-3, 3)\n",
    "\n",
    "plt.ylim(-3, 3)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "We will now define a measure that uses standard units to quantify the kinds of association that we have seen."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The correlation coefficient\n",
    "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.\n",
    "\n",
    "The term *correlation coefficient* isn't easy to say, so it is usually shortened to *correlation* and denoted by $r$.\n",
    "\n",
    "Here are some mathematical facts about $r$ that we will just observe by simulation.\n",
    "\n",
    "- The correlation coefficient $r$ is a number between $-1$ and 1.\n",
    "- $r$ measures the extent to which the scatter plot clusters around a straight line.\n",
    "- $r = 1$ if the scatter diagram is a perfect straight line sloping upwards, and $r = -1$ if the scatter diagram is a perfect straight line sloping downwards."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function ``r_scatter`` takes a value of $r$ as its argument and simulates a scatter plot with a correlation very close to $r$. Because of randomness in the simulation, the correlation is not expected to be exactly equal to $r$.\n",
    "\n",
    "Call ``r_scatter`` a few times, with different values of $r$ as the argument, and see how the scatter plot changes. \n",
    "\n",
    "When $r=1$ the scatter plot is perfectly linear and slopes upward. When $r=-1$, the scatter plot is perfectly linear and slopes downward. When $r=0$, the scatter plot is a formless cloud around the horizontal axis, and the variables are said to be *uncorrelated*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 18780 characters]\n",
      "text/plain": [
       "<Figure size 360x360 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "r_scatter(0.9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30060 characters]\n",
      "text/plain": [
       "<Figure size 360x360 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "r_scatter(0.25)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 29908 characters]\n",
      "text/plain": [
       "<Figure size 360x360 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "r_scatter(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 27432 characters]\n",
      "text/plain": [
       "<Figure size 360x360 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "r_scatter(-0.55)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Calculating $r$\n",
    "\n",
    "The formula for $r$ 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 $r$.\n",
    "\n",
    "**Formula for $r$**:\n",
    "\n",
    "**$r$ is the average of the products of the two variables, when both variables are measured in standard units.**\n",
    "\n",
    "Here are the steps in the calculation. We will apply the steps to a simple table of values of $x$ and $y$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>x</th>\n",
       "      <th>y</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   x  y\n",
       "0  1  2\n",
       "1  2  3\n",
       "2  3  1\n",
       "3  4  5\n",
       "4  5  2\n",
       "5  6  7"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = np.arange(1, 7, 1)\n",
    "y = np.array([2, 3, 1, 5, 2, 7])\n",
    "t = pd.DataFrame({'x':x,\n",
    "        'y':y})\n",
    "t"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Based on the scatter diagram, we expect that $r$ will be positive but not equal to 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 8068 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "t.plot.scatter(0, 1, s=30, color='red')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Step 1.** Convert each variable to standard units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>x</th>\n",
       "      <th>y</th>\n",
       "      <th>x (standard units)</th>\n",
       "      <th>y (standard units)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>-1.46385</td>\n",
       "      <td>-0.648886</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>-0.87831</td>\n",
       "      <td>-0.162221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>-0.29277</td>\n",
       "      <td>-1.135550</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>0.29277</td>\n",
       "      <td>0.811107</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>0.87831</td>\n",
       "      <td>-0.648886</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>1.46385</td>\n",
       "      <td>1.784436</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   x  y  x (standard units)  y (standard units)\n",
       "0  1  2            -1.46385           -0.648886\n",
       "1  2  3            -0.87831           -0.162221\n",
       "2  3  1            -0.29277           -1.135550\n",
       "3  4  5             0.29277            0.811107\n",
       "4  5  2             0.87831           -0.648886\n",
       "5  6  7             1.46385            1.784436"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t_su = t.copy()\n",
    "\n",
    "t_su['x (standard units)'] = standard_units(x)\n",
    "\n",
    "t_su['y (standard units)'] = standard_units(y)\n",
    "\n",
    "t_su"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Step 2.** Multiply each pair of standard units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>x</th>\n",
       "      <th>y</th>\n",
       "      <th>x (standard units)</th>\n",
       "      <th>y (standard units)</th>\n",
       "      <th>product of standard units</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>-1.46385</td>\n",
       "      <td>-0.648886</td>\n",
       "      <td>0.949871</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>-0.87831</td>\n",
       "      <td>-0.162221</td>\n",
       "      <td>0.142481</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>-0.29277</td>\n",
       "      <td>-1.135550</td>\n",
       "      <td>0.332455</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>0.29277</td>\n",
       "      <td>0.811107</td>\n",
       "      <td>0.237468</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "      <td>0.87831</td>\n",
       "      <td>-0.648886</td>\n",
       "      <td>-0.569923</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>1.46385</td>\n",
       "      <td>1.784436</td>\n",
       "      <td>2.612146</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   x  y  x (standard units)  y (standard units)  product of standard units\n",
       "0  1  2            -1.46385           -0.648886                   0.949871\n",
       "1  2  3            -0.87831           -0.162221                   0.142481\n",
       "2  3  1            -0.29277           -1.135550                   0.332455\n",
       "3  4  5             0.29277            0.811107                   0.237468\n",
       "4  5  2             0.87831           -0.648886                  -0.569923\n",
       "5  6  7             1.46385            1.784436                   2.612146"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t_product = t_su.copy()\n",
    "\n",
    "t_product['product of standard units'] = t_su.iloc[:,2] * t_su.iloc[:,3]\n",
    "\n",
    "t_product"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Step 3.** $r$ is the average of the products computed in Step 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6174163971897709"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# r is the average of the products of standard units\n",
    "\n",
    "r = np.mean(t_product.iloc[:,4])\n",
    "r"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, $r$ is positive but not equal to 1."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Properties of $r$\n",
    "The calculation shows that:\n",
    "\n",
    "- $r$ is a pure number. It has no units. This is because $r$ is based on standard units.\n",
    "- $r$ is unaffected by changing the units on either axis. This too is because $r$ is based on standard units.\n",
    "- $r$ is unaffected by switching the axes. Algebraically, this is because the product of standard units does not depend on which variable is called $x$ and which $y$. Geometrically, switching axes reflects the scatter plot about the line $y=x$, but does not change the amount of clustering nor the sign of the association."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 8192 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "t.plot.scatter('y', 'x', s=30, color='red')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The `correlation` function\n",
    "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 $r$, the mean of the products of those column values in standard units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def correlation(t, x, y):\n",
    "    return np.mean(standard_units(t[x])*standard_units(t[y]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's call the function on the ``x`` and ``y`` columns of ``t``. The function returns the same answer to the correlation between $x$ and $y$ as we got by direct application of the formula for $r$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6174163971897709"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(t, 'x', 'y')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we noticed, the order in which the variables are specified doesn't matter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6174163971897709"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(t, 'y', 'x')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.6667143635709919"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(suv, 'mpg', 'msrp')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.4869979927995918"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(suv, 'acceleration', 'msrp')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These values confirm what we had observed: \n",
    "\n",
    "- There is a negative association between price and efficiency, whereas the association between price and acceleration is positive.\n",
    "- The linear relation between price and acceleration is a little weaker (correlation about 0.5) than between price and mileage (correlation about -0.67). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Correlation is a simple and powerful concept, but it is sometimes misused. Before using $r$, it is important to be aware of what correlation does and does not measure."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Association is not Causation\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Correlation Measures *Linear* Association\n",
    "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 = x^2$ but have correlation equal to 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 11588 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "new_x = np.arange(-4, 4.1, 0.5)\n",
    "nonlinear = pd.DataFrame(\n",
    "        {'x':new_x,\n",
    "        'y':new_x**2}\n",
    "    )\n",
    "nonlinear.plot.scatter('x', 'y', s=30, color='r')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(nonlinear, 'x', 'y')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Correlation is Affected by Outliers\n",
    "Outliers can have a big effect on correlation. Here is an example where a scatter plot for which $r$ is equal to 1 is turned into a plot for which $r$ is equal to 0, by the addition of just one outlying point."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 10308 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "line = pd.DataFrame(\n",
    "        {'x':np.array([1, 2, 3, 4]),\n",
    "        'y':np.array([1, 2, 3, 4])}\n",
    "    )\n",
    "line.plot.scatter('x', 'y', s=30, color='r')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(line, 'x', 'y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 7024 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "outlier = pd.DataFrame(\n",
    "        {'x':np.array([1, 2, 3, 4, 5]),\n",
    "        'y':np.array([1, 2, 3, 4, 0])}\n",
    "    )\n",
    "outlier.plot.scatter('x', 'y', s=30, color='r')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(outlier, 'x', 'y')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Ecological Correlations Should be Interpreted with Care\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>State</th>\n",
       "      <th>Participation Rate</th>\n",
       "      <th>Critical Reading</th>\n",
       "      <th>Math</th>\n",
       "      <th>Writing</th>\n",
       "      <th>Combined</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>Alabama</td>\n",
       "      <td>6.7</td>\n",
       "      <td>547</td>\n",
       "      <td>538</td>\n",
       "      <td>532</td>\n",
       "      <td>1617</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>34</th>\n",
       "      <td>Alaska</td>\n",
       "      <td>54.2</td>\n",
       "      <td>507</td>\n",
       "      <td>503</td>\n",
       "      <td>475</td>\n",
       "      <td>1485</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>26</th>\n",
       "      <td>Arizona</td>\n",
       "      <td>36.4</td>\n",
       "      <td>522</td>\n",
       "      <td>525</td>\n",
       "      <td>500</td>\n",
       "      <td>1547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>Arkansas</td>\n",
       "      <td>4.2</td>\n",
       "      <td>573</td>\n",
       "      <td>571</td>\n",
       "      <td>554</td>\n",
       "      <td>1698</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>33</th>\n",
       "      <td>California</td>\n",
       "      <td>60.3</td>\n",
       "      <td>498</td>\n",
       "      <td>510</td>\n",
       "      <td>496</td>\n",
       "      <td>1504</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>Colorado</td>\n",
       "      <td>14.3</td>\n",
       "      <td>582</td>\n",
       "      <td>586</td>\n",
       "      <td>567</td>\n",
       "      <td>1735</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>Connecticut</td>\n",
       "      <td>88.4</td>\n",
       "      <td>507</td>\n",
       "      <td>510</td>\n",
       "      <td>508</td>\n",
       "      <td>1525</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>49</th>\n",
       "      <td>Delaware</td>\n",
       "      <td>100.0</td>\n",
       "      <td>456</td>\n",
       "      <td>459</td>\n",
       "      <td>444</td>\n",
       "      <td>1359</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50</th>\n",
       "      <td>District of Columbia</td>\n",
       "      <td>100.0</td>\n",
       "      <td>440</td>\n",
       "      <td>438</td>\n",
       "      <td>431</td>\n",
       "      <td>1309</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>43</th>\n",
       "      <td>Florida</td>\n",
       "      <td>72.2</td>\n",
       "      <td>491</td>\n",
       "      <td>485</td>\n",
       "      <td>472</td>\n",
       "      <td>1448</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                   State  Participation Rate  Critical Reading  Math  Writing  \\\n",
       "21               Alabama                 6.7               547   538      532   \n",
       "34                Alaska                54.2               507   503      475   \n",
       "26               Arizona                36.4               522   525      500   \n",
       "15              Arkansas                 4.2               573   571      554   \n",
       "33            California                60.3               498   510      496   \n",
       "12              Colorado                14.3               582   586      567   \n",
       "30           Connecticut                88.4               507   510      508   \n",
       "49              Delaware               100.0               456   459      444   \n",
       "50  District of Columbia               100.0               440   438      431   \n",
       "43               Florida                72.2               491   485      472   \n",
       "\n",
       "    Combined  \n",
       "21      1617  \n",
       "34      1485  \n",
       "26      1547  \n",
       "15      1698  \n",
       "33      1504  \n",
       "12      1735  \n",
       "30      1525  \n",
       "49      1359  \n",
       "50      1309  \n",
       "43      1448  "
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sat2014 = pd.read_csv(path_data + 'sat2014.csv').sort_values(by=['State'])\n",
    "sat2014.head(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 16156 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sat2014.plot.scatter('Critical Reading', 'Math')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9847558411067431"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correlation(sat2014, 'Critical Reading', 'Math')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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*. \n",
    "\n",
    "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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Serious or tongue-in-cheek?\n",
    "In 2012, a [paper](http://www.biostat.jhsph.edu/courses/bio621/misc/Chocolate%20consumption%20cognitive%20function%20and%20nobel%20laurates%20%28NEJM%29.pdf) 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](http://blogs.scientificamerican.com/the-curious-wavefunction/chocolate-consumption-and-nobel-prizes-a-bizarre-juxtaposition-if-there-ever-was-one/) responded seriously whereas\n",
    "[others](http://www.reuters.com/article/2012/10/10/us-eat-chocolate-win-the-nobel-prize-idUSBRE8991MS20121010#vFdfFkbPVlilSjsB.97) 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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "source": [
    "![Choco-Nobel](../../images/chocoNobel.png)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
