{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ".. _grid_tutorial:\n",
    "\n",
    ".. currentmodule:: seaborn"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Building structured multi-plot grids\n",
    "====================================\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "When exploring multi-dimensional data, a useful approach is to draw multiple instances of the same plot on different subsets of your dataset. This technique is sometimes called either \"lattice\" or \"trellis\" plotting, and it is related to the idea of `\"small multiples\" <https://en.wikipedia.org/wiki/Small_multiple>`_. It allows a viewer to quickly extract a large amount of information about a complex dataset. Matplotlib offers good support for making figures with multiple axes; seaborn builds on top of this to directly link the structure of the plot to the structure of your dataset.\n",
    "\n",
    "The :doc:`figure-level <function_overview>` functions are built on top of the objects discussed in this chapter of the tutorial. In most cases, you will want to work with those functions. They take care of some important bookkeeping that synchronizes the multiple plots in each grid. This chapter explains how the underlying objects work, which may be useful for advanced applications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide"
    ]
   },
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide"
    ]
   },
   "outputs": [],
   "source": [
    "sns.set_theme(style=\"ticks\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide"
    ]
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import numpy as np\n",
    "np.random.seed(sum(map(ord, \"axis_grids\")))"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ".. _facet_grid:\n",
    "\n",
    "Conditional small multiples\n",
    "---------------------------\n",
    "\n",
    "The :class:`FacetGrid` class is useful when you want to visualize the distribution of a variable or the relationship between multiple variables separately within subsets of your dataset. A :class:`FacetGrid` can be drawn with up to three dimensions: ``row``, ``col``, and ``hue``. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.\n",
    "\n",
    "Each of :func:`relplot`, :func:`displot`, :func:`catplot`, and :func:`lmplot` use this object internally, and they return the object when they are finished so that it can be used for further tweaking.\n",
    "\n",
    "The class is used by initializing a :class:`FacetGrid` object with a dataframe and the names of the variables that will form the row, column, or hue dimensions of the grid. These variables should be categorical or discrete, and then the data at each level of the variable will be used for a facet along that axis. For example, say we wanted to examine differences between lunch and dinner in the ``tips`` dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tips = sns.load_dataset(\"tips\")\n",
    "g = sns.FacetGrid(tips, col=\"time\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Initializing the grid like this sets up the matplotlib figure and axes, but doesn't draw anything on them.\n",
    "\n",
    "The main approach for visualizing data on this grid is with the :meth:`FacetGrid.map` method. Provide it with a plotting function and the name(s) of variable(s) in the dataframe to plot. Let's look at the distribution of tips in each of these subsets, using a histogram:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\")\n",
    "g.map(sns.histplot, \"tip\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "This function will draw the figure and annotate the axes, hopefully producing a finished plot in one step. To make a relational plot, just pass multiple variable names. You can also provide keyword arguments, which will be passed to the plotting function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"sex\", hue=\"smoker\")\n",
    "g.map(sns.scatterplot, \"total_bill\", \"tip\", alpha=.7)\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "There are several options for controlling the look of the grid that can be passed to the class constructor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, row=\"smoker\", col=\"time\", margin_titles=True)\n",
    "g.map(sns.regplot, \"size\", \"total_bill\", color=\".3\", fit_reg=False, x_jitter=.1)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Note that ``margin_titles`` isn't formally supported by the matplotlib API, and may not work well in all cases. In particular, it currently can't be used with a legend that lies outside of the plot.\n",
    "\n",
    "The size of the figure is set by providing the height of *each* facet, along with the aspect ratio:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"day\", height=4, aspect=.5)\n",
    "g.map(sns.barplot, \"sex\", \"total_bill\", order=[\"Male\", \"Female\"])"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The default ordering of the facets is derived from the information in the DataFrame. If the variable used to define facets has a categorical type, then the order of the categories is used. Otherwise, the facets will be in the order of appearance of the category levels. It is possible, however, to specify an ordering of any facet dimension with the appropriate ``*_order`` parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ordered_days = tips.day.value_counts().index\n",
    "g = sns.FacetGrid(tips, row=\"day\", row_order=ordered_days,\n",
    "                  height=1.7, aspect=4,)\n",
    "g.map(sns.kdeplot, \"total_bill\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Any seaborn color palette (i.e., something that can be passed to :func:`color_palette()`) can be provided. You can also use a dictionary that maps the names of values in the ``hue`` variable to valid matplotlib colors:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pal = dict(Lunch=\"seagreen\", Dinner=\".7\")\n",
    "g = sns.FacetGrid(tips, hue=\"time\", palette=pal, height=5)\n",
    "g.map(sns.scatterplot, \"total_bill\", \"tip\", s=100, alpha=.5)\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "If you have many levels of one variable, you can plot it along the columns but \"wrap\" them so that they span multiple rows. When doing this, you cannot use a ``row`` variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "attend = sns.load_dataset(\"attention\").query(\"subject <= 12\")\n",
    "g = sns.FacetGrid(attend, col=\"subject\", col_wrap=4, height=2, ylim=(0, 10))\n",
    "g.map(sns.pointplot, \"solutions\", \"score\", order=[1, 2, 3], color=\".3\", errorbar=None)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Once you've drawn a plot using :meth:`FacetGrid.map` (which can be called multiple times), you may want to adjust some aspects of the plot. There are also a number of methods on the :class:`FacetGrid` object for manipulating the figure at a higher level of abstraction. The most general is :meth:`FacetGrid.set`, and there are other more specialized methods like :meth:`FacetGrid.set_axis_labels`, which respects the fact that interior facets do not have axis labels. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with sns.axes_style(\"white\"):\n",
    "    g = sns.FacetGrid(tips, row=\"sex\", col=\"smoker\", margin_titles=True, height=2.5)\n",
    "g.map(sns.scatterplot, \"total_bill\", \"tip\", color=\"#334488\")\n",
    "g.set_axis_labels(\"Total bill (US Dollars)\", \"Tip\")\n",
    "g.set(xticks=[10, 30, 50], yticks=[2, 6, 10])\n",
    "g.figure.subplots_adjust(wspace=.02, hspace=.02)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "For even more customization, you can  work directly with the underling matplotlib ``Figure`` and ``Axes`` objects, which are stored as member attributes at ``figure`` and ``axes_dict``, respectively. When making a figure without row or column faceting, you can also use the ``ax`` attribute to directly access the single axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"smoker\", margin_titles=True, height=4)\n",
    "g.map(plt.scatter, \"total_bill\", \"tip\", color=\"#338844\", edgecolor=\"white\", s=50, lw=1)\n",
    "for ax in g.axes_dict.values():\n",
    "    ax.axline((0, 0), slope=.2, c=\".2\", ls=\"--\", zorder=0)\n",
    "g.set(xlim=(0, 60), ylim=(0, 14))"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ".. _custom_map_func:\n",
    "\n",
    "Using custom functions\n",
    "----------------------\n",
    "\n",
    "You're not limited to existing matplotlib and seaborn functions when using :class:`FacetGrid`. However, to work properly, any function you use must follow a few rules:\n",
    "\n",
    "1. It must plot onto the \"currently active\" matplotlib ``Axes``. This will be true of functions in the ``matplotlib.pyplot`` namespace, and you can call :func:`matplotlib.pyplot.gca` to get a reference to the current ``Axes`` if you want to work directly with its methods.\n",
    "2. It must accept the data that it plots in positional arguments. Internally, :class:`FacetGrid` will pass a ``Series`` of data for each of the named positional arguments passed to :meth:`FacetGrid.map`.\n",
    "3. It must be able to accept ``color`` and ``label`` keyword arguments, and, ideally, it will do something useful with them. In most cases, it's easiest to catch a generic dictionary of ``**kwargs`` and pass it along to the underlying plotting function.\n",
    "\n",
    "Let's look at minimal example of a function you can plot with. This function will just take a single vector of data for each facet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "def quantile_plot(x, **kwargs):\n",
    "    quantiles, xr = stats.probplot(x, fit=False)\n",
    "    plt.scatter(xr, quantiles, **kwargs)\n",
    "    \n",
    "g = sns.FacetGrid(tips, col=\"sex\", height=4)\n",
    "g.map(quantile_plot, \"total_bill\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "If we want to make a bivariate plot, you should write the function so that it accepts the x-axis variable first and the y-axis variable second:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def qqplot(x, y, **kwargs):\n",
    "    _, xr = stats.probplot(x, fit=False)\n",
    "    _, yr = stats.probplot(y, fit=False)\n",
    "    plt.scatter(xr, yr, **kwargs)\n",
    "    \n",
    "g = sns.FacetGrid(tips, col=\"smoker\", height=4)\n",
    "g.map(qqplot, \"total_bill\", \"tip\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Because :func:`matplotlib.pyplot.scatter` accepts ``color`` and ``label`` keyword arguments and does the right thing with them, we can add a hue facet without any difficulty:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, hue=\"time\", col=\"sex\", height=4)\n",
    "g.map(qqplot, \"total_bill\", \"tip\")\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Sometimes, though, you'll want to map a function that doesn't work the way you expect with the ``color`` and ``label`` keyword arguments. In this case, you'll want to explicitly catch them and handle them in the logic of your custom function. For example, this approach will allow use to map :func:`matplotlib.pyplot.hexbin`, which otherwise does not play well with the :class:`FacetGrid` API:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hexbin(x, y, color, **kwargs):\n",
    "    cmap = sns.light_palette(color, as_cmap=True)\n",
    "    plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs)\n",
    "\n",
    "with sns.axes_style(\"dark\"):\n",
    "    g = sns.FacetGrid(tips, hue=\"time\", col=\"time\", height=4)\n",
    "g.map(hexbin, \"total_bill\", \"tip\", extent=[0, 50, 0, 10]);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ".. _pair_grid:\n",
    "\n",
    "Plotting pairwise data relationships\n",
    "------------------------------------\n",
    "\n",
    ":class:`PairGrid` also allows you to quickly draw a grid of small subplots using the same plot type to visualize data in each. In a :class:`PairGrid`, each row and column is assigned to a different variable, so the resulting plot shows each pairwise relationship in the dataset. This style of plot is sometimes called a \"scatterplot matrix\", as this is the most common way to show each relationship, but :class:`PairGrid` is not limited to scatterplots.\n",
    "\n",
    "It's important to understand the differences between a :class:`FacetGrid` and a :class:`PairGrid`. In the former, each facet shows the same relationship conditioned on different levels of other variables. In the latter, each plot shows a different relationship (although the upper and lower triangles will have mirrored plots). Using :class:`PairGrid` can give you a very quick, very high-level summary of interesting relationships in your dataset.\n",
    "\n",
    "The basic usage of the class is very similar to :class:`FacetGrid`. First you initialize the grid, then you pass plotting function to a ``map`` method and it will be called on each subplot. There is also a companion function, :func:`pairplot` that trades off some flexibility for faster plotting.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "iris = sns.load_dataset(\"iris\")\n",
    "g = sns.PairGrid(iris)\n",
    "g.map(sns.scatterplot)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It's possible to plot a different function on the diagonal to show the univariate distribution of the variable in each column. Note that the axis ticks won't correspond to the count or density axis of this plot, though."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(iris)\n",
    "g.map_diag(sns.histplot)\n",
    "g.map_offdiag(sns.scatterplot)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "A very common way to use this plot colors the observations by a separate categorical variable. For example, the iris dataset has four measurements for each of three different species of iris flowers so you can see how they differ."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(iris, hue=\"species\")\n",
    "g.map_diag(sns.histplot)\n",
    "g.map_offdiag(sns.scatterplot)\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "By default every numeric column in the dataset is used, but you can focus on particular relationships if you want."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(iris, vars=[\"sepal_length\", \"sepal_width\"], hue=\"species\")\n",
    "g.map(sns.scatterplot)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It's also possible to use a different function in the upper and lower triangles to emphasize different aspects of the relationship."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(iris)\n",
    "g.map_upper(sns.scatterplot)\n",
    "g.map_lower(sns.kdeplot)\n",
    "g.map_diag(sns.kdeplot, lw=3, legend=False)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The square grid with identity relationships on the diagonal is actually just a special case, and you can plot with different variables in the rows and columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(tips, y_vars=[\"tip\"], x_vars=[\"total_bill\", \"size\"], height=4)\n",
    "g.map(sns.regplot, color=\".3\")\n",
    "g.set(ylim=(-1, 11), yticks=[0, 5, 10])"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Of course, the aesthetic attributes are configurable. For instance, you can use a different palette (say, to show an ordering of the ``hue`` variable) and pass keyword arguments into the plotting functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(tips, hue=\"size\", palette=\"GnBu_d\")\n",
    "g.map(plt.scatter, s=50, edgecolor=\"white\")\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ":class:`PairGrid` is flexible, but to take a quick look at a dataset, it can be easier to use :func:`pairplot`. This function uses scatterplots and histograms by default, although a few other kinds will be added (currently, you can also plot regression plots on the off-diagonals and KDEs on the diagonal)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.pairplot(iris, hue=\"species\", height=2.5)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "You can also control the aesthetics of the plot with keyword arguments, and it returns the :class:`PairGrid` instance for further tweaking."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.pairplot(iris, hue=\"species\", palette=\"Set2\", diag_kind=\"kde\", height=2.5)"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "py310",
   "language": "python",
   "name": "py310"
  },
  "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.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
