{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide"
    ]
   },
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "sns.set_theme(style=\"ticks\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Calling the constructor requires a long-form data object. This initializes the grid, but doesn't plot anything on it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tips = sns.load_dataset(\"tips\")\n",
    "sns.FacetGrid(tips)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Assign column and/or row variables to add more subplots to the figure:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.FacetGrid(tips, col=\"time\", row=\"sex\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "To draw a plot on every facet, pass a function and the name of one or more columns in the dataframe to :meth:`FacetGrid.map`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\",  row=\"sex\")\n",
    "g.map(sns.scatterplot, \"total_bill\", \"tip\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The variable specification in :meth:`FacetGrid.map` requires a positional argument mapping, but if the function has a ``data`` parameter and accepts named variable assignments, you can also use :meth:`FacetGrid.map_dataframe`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\",  row=\"sex\")\n",
    "g.map_dataframe(sns.histplot, x=\"total_bill\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Notice how the bins have different widths in each facet. A separate plot is drawn on each facet, so if the plotting function derives any parameters from the data, they may not be shared across facets. You can pass additional keyword arguments to synchronize them. But when possible, using a figure-level function like :func:`displot` will take care of this bookkeeping for you:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\", row=\"sex\")\n",
    "g.map_dataframe(sns.histplot, x=\"total_bill\", binwidth=2, binrange=(0, 60))"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The :class:`FacetGrid` constructor accepts a ``hue`` parameter. Setting this will condition the data on another variable and make multiple plots in different colors. Where possible, label information is tracked so that a single legend can be drawn:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\", hue=\"sex\")\n",
    "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "When ``hue`` is set on the :class:`FacetGrid`, however, a separate plot is drawn for each level of the variable. If the plotting function understands ``hue``, it is better to let it handle that logic. But it is important to ensure that each facet will use the same hue mapping. In the sample ``tips`` data, the ``sex`` column has a categorical datatype, which ensures this. Otherwise, you may want to use the `hue_order` or similar parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\")\n",
    "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\", hue=\"sex\")\n",
    "g.add_legend()"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The size and shape of the plot is specified at the level of each subplot using the ``height`` and ``aspect`` parameters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"day\", height=3.5, aspect=.65)\n",
    "g.map(sns.histplot, \"total_bill\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "If the variable assigned to ``col`` has many levels, it is possible to \"wrap\" it so that it spans multiple rows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"size\", height=2.5, col_wrap=3)\n",
    "g.map(sns.histplot, \"total_bill\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "To add horizontal or vertical reference lines on every facet, use :meth:`FacetGrid.refline`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"time\", margin_titles=True)\n",
    "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n",
    "g.refline(y=tips[\"tip\"].median())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can pass custom functions to plot with, or to annotate each facet. Your custom function must use the matplotlib state-machine interface to plot on the \"current\" axes, and it should catch additional keyword arguments:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "def annotate(data, **kws):\n",
    "    n = len(data)\n",
    "    ax = plt.gca()\n",
    "    ax.text(.1, .6, f\"N = {n}\", transform=ax.transAxes)\n",
    "\n",
    "g = sns.FacetGrid(tips, col=\"time\")\n",
    "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n",
    "g.map_dataframe(annotate)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The :class:`FacetGrid` object has some other useful parameters and methods for tweaking the plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"sex\", row=\"time\", margin_titles=True)\n",
    "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n",
    "g.set_axis_labels(\"Total bill ($)\", \"Tip ($)\")\n",
    "g.set_titles(col_template=\"{col_name} patrons\", row_template=\"{row_name}\")\n",
    "g.set(xlim=(0, 60), ylim=(0, 12), xticks=[10, 30, 50], yticks=[2, 6, 10])\n",
    "g.tight_layout()\n",
    "g.savefig(\"facet_plot.png\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide"
    ]
   },
   "outputs": [],
   "source": [
    "import os\n",
    "if os.path.exists(\"facet_plot.png\"):\n",
    "    os.remove(\"facet_plot.png\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "You also have access to the underlying matplotlib objects for additional tweaking:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.FacetGrid(tips, col=\"sex\", row=\"time\", margin_titles=True, despine=False)\n",
    "g.map_dataframe(sns.scatterplot, x=\"total_bill\", y=\"tip\")\n",
    "g.figure.subplots_adjust(wspace=0, hspace=0)\n",
    "for (row_val, col_val), ax in g.axes_dict.items():\n",
    "    if row_val == \"Lunch\" and col_val == \"Female\":\n",
    "        ax.set_facecolor(\".95\")\n",
    "    else:\n",
    "        ax.set_facecolor((0, 0, 0, 0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "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
}
