{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pairplots in Python\n",
    "\n",
    "In this notebook we will explore making pairplots in Python using the seaborn visualization library. We'll start with the default `sns.pairplot` and then look at customizing our plots using `sns.PairGrids`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pandas and numpy for data manipulation\n",
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# matplotlib for plotting\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib\n",
    "\n",
    "# Set text size\n",
    "matplotlib.rcParams['font.size'] = 18\n",
    "\n",
    "# Seaborn for pairplots\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_context('talk', font_scale=1.2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Gapminder Socioeconomic Data\n",
    "\n",
    "We will be using [GapMinder socioeconomic data](https://cran.r-project.org/web/packages/gapminder/README.html) that is available in the R package `gapminder`. The data has been saved to a csv file which we will read into a dataframe. There are six columns in the data:\n",
    "\n",
    "1. Country\n",
    "2. Continent: useful for grouping data\n",
    "3. Year: data coveres 1952-2007\n",
    "4. life_exp: the life expectancy at birth \n",
    "5. pop: population\n",
    "6. gdp_per_cap: the per capita (per person) GDP in [international dollars](https://en.wikipedia.org/wiki/Geary%E2%80%93Khamis_dollar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "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>country</th>\n",
       "      <th>continent</th>\n",
       "      <th>year</th>\n",
       "      <th>life_exp</th>\n",
       "      <th>pop</th>\n",
       "      <th>gdp_per_cap</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1952</td>\n",
       "      <td>28.801</td>\n",
       "      <td>8425333</td>\n",
       "      <td>779.445314</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1957</td>\n",
       "      <td>30.332</td>\n",
       "      <td>9240934</td>\n",
       "      <td>820.853030</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1962</td>\n",
       "      <td>31.997</td>\n",
       "      <td>10267083</td>\n",
       "      <td>853.100710</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1967</td>\n",
       "      <td>34.020</td>\n",
       "      <td>11537966</td>\n",
       "      <td>836.197138</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1972</td>\n",
       "      <td>36.088</td>\n",
       "      <td>13079460</td>\n",
       "      <td>739.981106</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       country continent  year  life_exp       pop  gdp_per_cap\n",
       "0  Afghanistan      Asia  1952    28.801   8425333   779.445314\n",
       "1  Afghanistan      Asia  1957    30.332   9240934   820.853030\n",
       "2  Afghanistan      Asia  1962    31.997  10267083   853.100710\n",
       "3  Afghanistan      Asia  1967    34.020  11537966   836.197138\n",
       "4  Afghanistan      Asia  1972    36.088  13079460   739.981106"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.read_csv('data/gapminder_data.csv')\n",
    "df.columns = ['country', 'continent', 'year', 'life_exp', 'pop', 'gdp_per_cap']\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can quickly find summary stats for the data using the `describe` method of a dataframe."
   ]
  },
  {
   "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>year</th>\n",
       "      <th>life_exp</th>\n",
       "      <th>pop</th>\n",
       "      <th>gdp_per_cap</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>1704.00000</td>\n",
       "      <td>1704.000000</td>\n",
       "      <td>1.704000e+03</td>\n",
       "      <td>1704.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>1979.50000</td>\n",
       "      <td>59.474439</td>\n",
       "      <td>2.960121e+07</td>\n",
       "      <td>7215.327081</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>17.26533</td>\n",
       "      <td>12.917107</td>\n",
       "      <td>1.061579e+08</td>\n",
       "      <td>9857.454543</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1952.00000</td>\n",
       "      <td>23.599000</td>\n",
       "      <td>6.001100e+04</td>\n",
       "      <td>241.165877</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>1965.75000</td>\n",
       "      <td>48.198000</td>\n",
       "      <td>2.793664e+06</td>\n",
       "      <td>1202.060309</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>1979.50000</td>\n",
       "      <td>60.712500</td>\n",
       "      <td>7.023596e+06</td>\n",
       "      <td>3531.846989</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>1993.25000</td>\n",
       "      <td>70.845500</td>\n",
       "      <td>1.958522e+07</td>\n",
       "      <td>9325.462346</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>2007.00000</td>\n",
       "      <td>82.603000</td>\n",
       "      <td>1.318683e+09</td>\n",
       "      <td>113523.132900</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             year     life_exp           pop    gdp_per_cap\n",
       "count  1704.00000  1704.000000  1.704000e+03    1704.000000\n",
       "mean   1979.50000    59.474439  2.960121e+07    7215.327081\n",
       "std      17.26533    12.917107  1.061579e+08    9857.454543\n",
       "min    1952.00000    23.599000  6.001100e+04     241.165877\n",
       "25%    1965.75000    48.198000  2.793664e+06    1202.060309\n",
       "50%    1979.50000    60.712500  7.023596e+06    3531.846989\n",
       "75%    1993.25000    70.845500  1.958522e+07    9325.462346\n",
       "max    2007.00000    82.603000  1.318683e+09  113523.132900"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Default Pair Plot with All Data\n",
    "\n",
    "Let's use the entire dataset and `sns.pairplot` to create a simple, yet useful plot. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 161348 characters]\n",
      "text/plain": [
       "<Figure size 720x720 with 20 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.pairplot(df);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The default pairplot shows scatter plots between variables on the upper and lower triangle and histograms along the diagonal. Already, we can see some trends such as a positive correlation between `gdp_per_cap` and `life_exp` and `year` and `life_exp` which suggests that people in richer countries live longer and that in general, people have been living longer as time increases. We can't say what causes theses trends, only that there is a correlation. \n",
    "\n",
    "We can also see that the distribution of `pop` and `gdp_per_cap` is heavily skewed to the right. To better represent the data, we can take the log transform of those columns. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "df['log_pop'] = np.log10(df['pop'])\n",
    "df['log_gdp_per_cap'] = np.log10(df['gdp_per_cap'])\n",
    "\n",
    "df = df.drop(columns = ['pop', 'gdp_per_cap'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Group and Color by a Variable\n",
    "\n",
    "In order to better understand the data, we can color the `pairplot` using a categorical variable and the `hue` keyword. First, we will color the plots by the continent. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 209588 characters]\n",
      "text/plain": [
       "<Figure size 848.785x720 with 20 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "matplotlib.rcParams['font.size'] = 40\n",
    "sns.pairplot(df, hue = 'continent');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I don't find stacked histograms (on the diagonal) to be very useful, and there are some issues with overlapping data points (known as overplotting). We can fix these by adding in a few customizations to the `pairplot` call. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Customizing `pairplot`\n",
    "\n",
    "First, let's change the diagonal from a histogram to a kde which can better show the differences between continents. We can also adjust the alpha (intensity) of the scatter plots to better show all the data and change the size of the markers on the scatter plot. Finally, I increase the size of all the plots to better show the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 740420 characters]\n",
      "text/plain": [
       "<Figure size 1280.78x1152 with 20 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.pairplot(df, hue = 'continent', diag_kind = 'kde', plot_kws = {'alpha': 0.6, 's': 80, 'edgecolor': 'k'}, size = 4);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That makes some of the trends more clear. We can see that Oceania and Europe tend to have the highest life expectancy and highest GDP with Asian countries tending to have the greatest population. The density plots on the diagonal are better for when we have data in multiple categories to make comparisons. We can color the plot by any variable we like. For example, here is a plot colored by a decade categorical variable we create from the year column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "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>country</th>\n",
       "      <th>continent</th>\n",
       "      <th>year</th>\n",
       "      <th>life_exp</th>\n",
       "      <th>log_pop</th>\n",
       "      <th>log_gdp_per_cap</th>\n",
       "      <th>decade</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1952</td>\n",
       "      <td>28.801</td>\n",
       "      <td>6.925587</td>\n",
       "      <td>2.891786</td>\n",
       "      <td>(1950, 1960]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1957</td>\n",
       "      <td>30.332</td>\n",
       "      <td>6.965716</td>\n",
       "      <td>2.914265</td>\n",
       "      <td>(1950, 1960]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1962</td>\n",
       "      <td>31.997</td>\n",
       "      <td>7.011447</td>\n",
       "      <td>2.931000</td>\n",
       "      <td>(1960, 1970]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1967</td>\n",
       "      <td>34.020</td>\n",
       "      <td>7.062129</td>\n",
       "      <td>2.922309</td>\n",
       "      <td>(1960, 1970]</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Afghanistan</td>\n",
       "      <td>Asia</td>\n",
       "      <td>1972</td>\n",
       "      <td>36.088</td>\n",
       "      <td>7.116590</td>\n",
       "      <td>2.869221</td>\n",
       "      <td>(1970, 1980]</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       country continent  year  life_exp   log_pop  log_gdp_per_cap  \\\n",
       "0  Afghanistan      Asia  1952    28.801  6.925587         2.891786   \n",
       "1  Afghanistan      Asia  1957    30.332  6.965716         2.914265   \n",
       "2  Afghanistan      Asia  1962    31.997  7.011447         2.931000   \n",
       "3  Afghanistan      Asia  1967    34.020  7.062129         2.922309   \n",
       "4  Afghanistan      Asia  1972    36.088  7.116590         2.869221   \n",
       "\n",
       "         decade  \n",
       "0  (1950, 1960]  \n",
       "1  (1950, 1960]  \n",
       "2  (1960, 1970]  \n",
       "3  (1960, 1970]  \n",
       "4  (1970, 1980]  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['decade'] = pd.cut(df['year'], bins = range(1950, 2010, 10))\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 440800 characters]\n",
      "text/plain": [
       "<Figure size 1022.28x864 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.pairplot(df, hue = 'decade', diag_kind = 'kde', vars = ['life_exp', 'log_pop', 'log_gdp_per_cap'],\n",
    "             plot_kws = {'alpha': 0.6, 's': 80, 'edgecolor': 'k'}, size = 4);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, we can know see that life expectancy has increased over the decades as has population. Retaining the year variable might not make much sense when we are already coloring by the decade."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is still quite a lot of noise on the scatter plots, mostly because we are plotting many years at once. Let's limit ourselves to the most recent year in the data. Notice how we must now use the `vars` keyword to specify the variables we want to plot. It does not make sense to plot the year variable since it no longer varies. We will limit the plot to the three remaining numerical variables. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 288612 characters]\n",
      "text/plain": [
       "<Figure size 992.785x864 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.pairplot(df[df['year'] >= 2000], vars = ['life_exp', 'log_pop', 'log_gdp_per_cap'], \n",
    "             hue = 'continent', diag_kind = 'kde', plot_kws = {'alpha': 0.6, 's': 80, 'edgecolor': 'k'}, size = 4);\n",
    "plt.suptitle('Pair Plot of Socioeconomic Data for 2000-2007', size = 28);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# More Customization with `sns.PairGrid` \n",
    "\n",
    "When the options offered by pairplot are not enough, we can move on to more powerful PairGrid. This allows us to define our own functions to map to the lower and upper triangles and the diagonal. For example, we might want a plot that instead of showing two instaces of the scatter plots, shows the [Pearson Correlation coefficient](http://www.statisticshowto.com/probability-and-statistics/correlation-coefficient-formula/) (a measure of a linear trend) on one of the triangles. To do this, we can just write a function to calculate the statistic and then map it to the appropriate part of the plot."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, we will show the basic usage of `sns.PairGrid`. Here, we map a scatter plot to the upper triangle, a density plot to the diagonal, and a 2D density plot to the lower triangle. `PairGrid` is a class and not a function, which means that we need to create an instance and then use methods of that instance to build a plot. Then, after we have added all the methods to the instance, we can show the resulting plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 119600 characters]\n",
      "text/plain": [
       "<Figure size 864x864 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Create an instance of the PairGrid class.\n",
    "grid = sns.PairGrid(data= df[df['year'] == 2007],\n",
    "                    vars = ['life_exp', 'log_pop', 'log_gdp_per_cap'], size = 4)\n",
    "\n",
    "# Map different plots to different sections\n",
    "grid = grid.map_upper(plt.scatter, color = 'darkred')\n",
    "grid = grid.map_lower(sns.kdeplot, cmap = 'Reds')\n",
    "grid = grid.map_diag(plt.hist, bins = 10, color = 'darkred', edgecolor = 'k');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we see how to map different functions to the different elements, we can write out own function to put on the plot. We'll use a simple function to show the correlation coffiecients on the scatterplot. (Thanks to this [Stack Overflow answer](https://stackoverflow.com/questions/30942577/seaborn-correlation-coefficient-on-pairgrid) for help on how to write a custom function and map it onto the plot)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 123964 characters]\n",
      "text/plain": [
       "<Figure size 864x864 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Function to calculate correlation coefficient between two arrays\n",
    "def corr(x, y, **kwargs):\n",
    "    \n",
    "    # Calculate the value\n",
    "    coef = np.corrcoef(x, y)[0][1]\n",
    "    # Make the label\n",
    "    label = r'$\\rho$ = ' + str(round(coef, 2))\n",
    "    \n",
    "    # Add the label to the plot\n",
    "    ax = plt.gca()\n",
    "    ax.annotate(label, xy = (0.2, 0.95), size = 20, xycoords = ax.transAxes)\n",
    "    \n",
    "# Create a pair grid instance\n",
    "grid = sns.PairGrid(data= df[df['year'] == 2007],\n",
    "                    vars = ['life_exp', 'log_pop', 'log_gdp_per_cap'], size = 4)\n",
    "\n",
    "# Map the plots to the locations\n",
    "grid = grid.map_upper(plt.scatter, color = 'darkred')\n",
    "grid = grid.map_upper(corr)\n",
    "grid = grid.map_lower(sns.kdeplot, cmap = 'Reds')\n",
    "grid = grid.map_diag(plt.hist, bins = 10, edgecolor =  'k', color = 'darkred');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can map any function we would like to any of the areas. For example, maybe we would like to show the summary stats on the diagonal."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 190036 characters]\n",
      "text/plain": [
       "<Figure size 864x864 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Define a summary function\n",
    "def summary(x, **kwargs):\n",
    "    # Convert to a pandas series\n",
    "    x = pd.Series(x)\n",
    "    \n",
    "    # Get stats for the series\n",
    "    label = x.describe()[['mean', 'std', 'min', '50%', 'max']]\n",
    "    \n",
    "    # Convert from log to regular scale\n",
    "    # Adjust the column names for presentation\n",
    "    if label.name == 'log_pop':\n",
    "        label = 10 ** label\n",
    "        label.name = 'pop stats'\n",
    "    elif label.name == 'log_gdp_per_cap':\n",
    "        label = 10 ** label\n",
    "        label.name = 'gdp_per_cap stats'\n",
    "    else:\n",
    "        label.name = 'life_exp stats'\n",
    "       \n",
    "    # Round the labels for presentation\n",
    "    label = label.round()\n",
    "    ax = plt.gca()\n",
    "    ax.set_axis_off()\n",
    "\n",
    "    # Add the labels to the plot\n",
    "    ax.annotate(pd.DataFrame(label),\n",
    "               xy = (0.1, 0.2), size = 20, xycoords = ax.transAxes)    \n",
    "    \n",
    "\n",
    "# Create a pair grid instance\n",
    "grid = sns.PairGrid(data= df[df['year'] == 2007],\n",
    "                    vars = ['life_exp', 'log_pop', 'log_gdp_per_cap'], size = 4)\n",
    "\n",
    "# Fill in the mappings\n",
    "grid = grid.map_upper(plt.scatter, color = 'darkred')\n",
    "grid = grid.map_upper(corr)\n",
    "grid = grid.map_lower(sns.kdeplot, cmap = 'Reds')\n",
    "grid = grid.map_diag(summary);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can extend this however we like in order to investigate the data. For most use cases, the `sns.pairplot` function will do everything we require, but if we need the extra options, we can always use the more powerful `sns.PairGrid`. Pair plots are a great method to get a first look at a dataset, and seaborn has extensive capabilities for producing these figures!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "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.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
