<commit_before>{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ".. _categorical_tutorial:\n",
    "\n",
    ".. currentmodule:: seaborn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plotting with categorical data"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "We :ref:`previously <regression_tutorial>` learned how to use scatterplots and regression model fits to visualize the relationship between two variables and how it changes across levels of additional categorical variables. However, what if one of the main variables you are interested in is categorical? In this case, the scatterplot and regression model approach won't work. There are several options, however, for visualizing such a relationship, which we will discuss in this tutorial.\n",
    "\n",
    "It's useful to divide seaborn's categorical plots into three groups: those that show each observation at each level of the categorical variable, those that show an abstract representation of each *distribution* of observations, and those that apply a statistical estimation to show a measure of central tendency and confidence interval. The first includes the functions :func:`swarmplot` and :func:`stripplot`, the second includes :func:`boxplot` and :func:`violinplot`, and the third includes :func:`barplot` and :func:`pointplot`. These functions all share a basic API for how they accept data, although each has specific parameters that control the particulars of the visualization that is applied to that data.\n",
    "\n",
    "Much like the relationship between :func:`regplot` and :func:`lmplot`, in seaborn there are both relatively low-level and relatively high-level approaches for making categorical plots. The functions named above are all low-level in that they plot onto a specific matplotlib axes. There is also the higher-level :func:`factorplot`, which combines these functions with a :class:`FacetGrid` to apply a categorical plot across a grid of figure panels.\n",
    "\n",
    "It is easiest and best to invoke these functions with a DataFrame that is in `\"tidy\" <https://vita.had.co.nz/papers/tidy-data.pdf>`_ format, although the lower-level functions also accept wide-form DataFrames or simple vectors of observations. See below for examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "sns.set(style=\"whitegrid\", color_codes=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(sum(map(ord, \"categorical\")))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "titanic = sns.load_dataset(\"titanic\")\n",
    "tips = sns.load_dataset(\"tips\")\n",
    "iris = sns.load_dataset(\"iris\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Categorical scatterplots\n",
    "------------------------\n",
    "\n",
    "A simple way to show the the values of some quantitative variable across the levels of a categorical variable uses :func:`stripplot`, which generalizes a scatterplot to the case where one of the variables is categorical:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.stripplot(x=\"day\", y=\"total_bill\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "In a strip plot, the scatterplot points will usually overlap. This makes it difficult to see the full distribution of data. One easy solution is to adjust the positions (only along the categorical axis) using some random \"jitter\": "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.stripplot(x=\"day\", y=\"total_bill\", data=tips, jitter=True);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "A different approach would be to use the function :func:`swarmplot`, which positions each scatterplot point on the categorical axis with an algorithm that avoids overlapping points:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It's also possible to add a nested categorical variable with the ``hue`` parameter. Above the color and position on the categorical axis are redundant, but now each provides information about one of the two variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "In general, the seaborn categorical plotting functions try to infer the order of categories from the data. If your data have a pandas ``Categorical`` datatype, then the default order of the categories can be set there. For other datatypes, string-typed categories will be plotted in the order they appear in the DataFrame, but categories that look numerical will be sorted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"size\", y=\"total_bill\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "With these plots, it's often helpful to put the categorical variable on the vertical axis (this is particularly useful when the category names are relatively long or there are many categories). You can force an orientation using the ``orient`` keyword, but usually plot orientation can be inferred from the datatypes of the variables passed to ``x`` and/or ``y``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"total_bill\", y=\"day\", hue=\"time\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Distributions of observations within categories\n",
    "-----------------------------------------------\n",
    "\n",
    "At a certain point, the categorical scatterplot approach becomes limited in the information it can provide about the distribution of values within each category. There are several ways to summarize this information in ways that facilitate easy comparisons across the category levels. These generalize some of the approaches we discussed in the :ref:`chapter <distribution_tutorial>` to the case where we want to quickly compare across several distributions.\n",
    "\n",
    "Boxplots\n",
    "^^^^^^^^\n",
    "\n",
    "The first is the familiar :func:`boxplot`. This kind of plot shows the three quartile values of the distribution along with extreme values. The \"whiskers\" extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. Importantly, this means that each value in the boxplot corresponds to an actual observation in the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"time\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "For boxplots, the assumption when using a ``hue`` variable is that it is nested within the ``x`` or ``y`` variable. This means that by default, the boxes for different levels of ``hue`` will be offset, as you can see above. If your ``hue`` variable is not nested, you can set the ``dodge`` parameter to disable offsetting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tips[\"weekend\"] = tips[\"day\"].isin([\"Sat\", \"Sun\"])\n",
    "sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"weekend\", data=tips, dodge=False);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Violinplots\n",
    "^^^^^^^^^^^\n",
    "\n",
    "A different approach is a :func:`violinplot`, which combines a boxplot with the kernel density estimation procedure described in the :ref:`distributions <distribution_tutorial>` tutorial:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"total_bill\", y=\"day\", hue=\"time\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "This approach uses the kernel density estimate to provide a better description of the distribution of values. Additionally, the quartile and whikser values from the boxplot are shown inside the violin. Because the violinplot uses a KDE, there are some other parameters that may need tweaking, adding some complexity relative to the straightforward boxplot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"total_bill\", y=\"day\", hue=\"time\", data=tips,\n",
    "               bw=.1, scale=\"count\", scale_hue=False);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It's also possible to \"split\" the violins when the hue parameter has only two levels, which can allow for a more efficient use of space:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips, split=True);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Finally, there are several options for the plot that is drawn on the interior of the violins, including ways to show each individual observation instead of the summary boxplot values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips,\n",
    "               split=True, inner=\"stick\", palette=\"Set3\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It can also be useful to combine :func:`swarmplot` or :func:`swarmplot` with :func:`violinplot` or :func:`boxplot` to show each observation along with a summary of the distribution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"day\", y=\"total_bill\", data=tips, inner=None)\n",
    "sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips, color=\"w\", alpha=.5);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Statistical estimation within categories\n",
    "----------------------------------------\n",
    "\n",
    "Often, rather than showing the distribution within each category, you might want to show the central tendency of the values. Seaborn has two main ways to show this information, but importantly, the basic API for these functions is identical to that for the ones discussed above.\n",
    "\n",
    "Bar plots\n",
    "^^^^^^^^^\n",
    "\n",
    "A familiar style of plot that accomplishes this goal is a bar plot. In seaborn, the :func:`barplot` function operates on a full dataset and shows an arbitrary estimate, using the mean by default. When there are multiple observations in each category, it also uses bootstrapping to compute a confidence interval around the estimate and plots that using error bars:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=\"sex\", y=\"survived\", hue=\"class\", data=titanic);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "A special case for the bar plot is when you want to show the number of observations in each category rather than computing a statistic for a second variable. This is similar to a histogram over a categorical, rather than quantitative, variable. In seaborn, it's easy to do so with the :func:`countplot` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.countplot(x=\"deck\", data=titanic, palette=\"Greens_d\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Both :func:`barplot` and :func:`countplot` can be invoked with all of the options discussed above, along with others that are demonstrated in the detailed documentation for each function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.countplot(y=\"deck\", hue=\"class\", data=titanic, palette=\"Greens_d\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Point plots\n",
    "^^^^^^^^^^^\n",
    "\n",
    "An alternative style for visualizing the same information is offered by the :func:`pointplot` function. This function also encodes the value of the estimate with height on the other axis, but rather than show a full bar it just plots the point estimate and confidence interval. Additionally, :func:`pointplot` connects points from the same ``hue`` category. This makes it easy to see how the main relationship is changing as a function of a second variable, because your eyes are quite good at picking up on differences of slopes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.pointplot(x=\"sex\", y=\"survived\", hue=\"class\", data=titanic);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "To make figures that reproduce well in black and white, it can be good to use different markers and line styles for the levels of the ``hue`` category:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.pointplot(x=\"class\", y=\"survived\", hue=\"sex\", data=titanic,\n",
    "              palette={\"male\": \"g\", \"female\": \"m\"},\n",
    "              markers=[\"^\", \"o\"], linestyles=[\"-\", \"--\"]);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Plotting \"wide-form\" data\n",
    "-------------------------\n",
    "\n",
    "While using \"long-form\" or \"tidy\" data is preferred, these functions can also by applied to \"wide-form\" data in a variety of formats, including pandas DataFrames or two-dimensional numpy arrays. These objects should be passed directly to the ``data`` parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(data=iris, orient=\"h\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Additionally, these functions accept vectors of Pandas or numpy objects rather than variables in a ``DataFrame``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=iris.species, y=iris.sepal_length);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "To control the size and shape of plots made by the functions discussed above, you must set up the figure yourself using matplotlib commands. Of course, this also means that the plots can happily coexist in a multi-panel figure with other kinds of plots:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f, ax = plt.subplots(figsize=(7, 3))\n",
    "sns.countplot(y=\"deck\", data=titanic, color=\"c\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Drawing multi-panel categorical plots\n",
    "-------------------------------------\n",
    "\n",
    "As we mentioned above, there are two ways to draw categorical plots in seaborn. Similar to the duality in the regression plots, you can either use the functions introduced above, or the higher-level function :func:`factorplot`, which combines these functions with a :func:`FacetGrid` to add the ability to examine additional categories through the larger structure of the figure. By default, :func:`factorplot` produces a :func:`pointplot`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "However, the ``kind`` parameter lets you chose any of the kinds of plots discussed above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=tips, kind=\"bar\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The main advantage of using a :func:`factorplot` is that it is very easy to \"facet\" the plot and investigate the role of other categorical variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n",
    "               col=\"time\", data=tips, kind=\"swarm\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Any kind of plot can be drawn. Because of the way :class:`FacetGrid` works, to change the size and shape of the figure you need to specify the ``size`` and ``aspect`` arguments, which apply to each facet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"time\", y=\"total_bill\", hue=\"smoker\",\n",
    "               col=\"day\", data=tips, kind=\"box\", size=4, aspect=.5);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It is important to note that you could also make this plot by using :func:`boxplot` and :class:`FacetGrid` directly. However, special care must be taken to ensure that the order of the categorical variables is enforced in each facet, either by using data with a ``Categorical`` datatype or by passing ``order`` and ``hue_order``.\n",
    "\n",
    "Because of the generalized API of the categorical plots, they should be easy to apply to other more complex contexts. For example, they are easily combined with a :class:`PairGrid` to show categorical relationships across several different variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(tips,\n",
    "                 x_vars=[\"smoker\", \"time\", \"sex\"],\n",
    "                 y_vars=[\"total_bill\", \"tip\"],\n",
    "                 aspect=.75, size=3.5)\n",
    "g.map(sns.violinplot, palette=\"pastel\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6  (seaborn-dev)",
   "language": "python",
   "name": "seaborn-dev"
  },
  "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
<commit_msg>Include lvplot<commit_after>{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    ".. _categorical_tutorial:\n",
    "\n",
    ".. currentmodule:: seaborn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plotting with categorical data"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "We :ref:`previously <regression_tutorial>` learned how to use scatterplots and regression model fits to visualize the relationship between two variables and how it changes across levels of additional categorical variables. However, what if one of the main variables you are interested in is categorical? In this case, the scatterplot and regression model approach won't work. There are several options, however, for visualizing such a relationship, which we will discuss in this tutorial.\n",
    "\n",
    "It's useful to divide seaborn's categorical plots into three groups: those that show each observation at each level of the categorical variable, those that show an abstract representation of each *distribution* of observations, and those that apply a statistical estimation to show a measure of central tendency and confidence interval. The first includes the functions :func:`swarmplot` and :func:`stripplot`, the second includes :func:`boxplot`, :func:`violinplot` and :func:`lvplot`, and the third includes :func:`barplot` and :func:`pointplot`. These functions all share a basic API for how they accept data, although each has specific parameters that control the particulars of the visualization that is applied to that data.\n",
    "\n",
    "Much like the relationship between :func:`regplot` and :func:`lmplot`, in seaborn there are both relatively low-level and relatively high-level approaches for making categorical plots. The functions named above are all low-level in that they plot onto a specific matplotlib axes. There is also the higher-level :func:`factorplot`, which combines these functions with a :class:`FacetGrid` to apply a categorical plot across a grid of figure panels.\n",
    "\n",
    "It is easiest and best to invoke these functions with a DataFrame that is in `\"tidy\" <https://vita.had.co.nz/papers/tidy-data.pdf>`_ format, although the lower-level functions also accept wide-form DataFrames or simple vectors of observations. See below for examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "sns.set(style=\"whitegrid\", color_codes=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(sum(map(ord, \"categorical\")))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "titanic = sns.load_dataset(\"titanic\")\n",
    "tips = sns.load_dataset(\"tips\")\n",
    "iris = sns.load_dataset(\"iris\")"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Categorical scatterplots\n",
    "------------------------\n",
    "\n",
    "A simple way to show the the values of some quantitative variable across the levels of a categorical variable uses :func:`stripplot`, which generalizes a scatterplot to the case where one of the variables is categorical:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.stripplot(x=\"day\", y=\"total_bill\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "In a strip plot, the scatterplot points will usually overlap. This makes it difficult to see the full distribution of data. One easy solution is to adjust the positions (only along the categorical axis) using some random \"jitter\": "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.stripplot(x=\"day\", y=\"total_bill\", data=tips, jitter=True);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "A different approach would be to use the function :func:`swarmplot`, which positions each scatterplot point on the categorical axis with an algorithm that avoids overlapping points:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It's also possible to add a nested categorical variable with the ``hue`` parameter. Above the color and position on the categorical axis are redundant, but now each provides information about one of the two variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "In general, the seaborn categorical plotting functions try to infer the order of categories from the data. If your data have a pandas ``Categorical`` datatype, then the default order of the categories can be set there. For other datatypes, string-typed categories will be plotted in the order they appear in the DataFrame, but categories that look numerical will be sorted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"size\", y=\"total_bill\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "With these plots, it's often helpful to put the categorical variable on the vertical axis (this is particularly useful when the category names are relatively long or there are many categories). You can force an orientation using the ``orient`` keyword, but usually plot orientation can be inferred from the datatypes of the variables passed to ``x`` and/or ``y``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.swarmplot(x=\"total_bill\", y=\"day\", hue=\"time\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Distributions of observations within categories\n",
    "-----------------------------------------------\n",
    "\n",
    "At a certain point, the categorical scatterplot approach becomes limited in the information it can provide about the distribution of values within each category. There are several ways to summarize this information in ways that facilitate easy comparisons across the category levels. These generalize some of the approaches we discussed in the :ref:`chapter <distribution_tutorial>` to the case where we want to quickly compare across several distributions.\n",
    "\n",
    "Boxplots\n",
    "^^^^^^^^\n",
    "\n",
    "The first is the familiar :func:`boxplot`. This kind of plot shows the three quartile values of the distribution along with extreme values. The \"whiskers\" extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall outside this range are displayed independently. Importantly, this means that each value in the boxplot corresponds to an actual observation in the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"time\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "For boxplots, the assumption when using a ``hue`` variable is that it is nested within the ``x`` or ``y`` variable. This means that by default, the boxes for different levels of ``hue`` will be offset, as you can see above. If your ``hue`` variable is not nested, you can set the ``dodge`` parameter to disable offsetting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tips[\"weekend\"] = tips[\"day\"].isin([\"Sat\", \"Sun\"])\n",
    "sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"weekend\", data=tips, dodge=False);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Violinplots\n",
    "^^^^^^^^^^^\n",
    "\n",
    "A different approach is a :func:`violinplot`, which combines a boxplot with the kernel density estimation procedure described in the :ref:`distributions <distribution_tutorial>` tutorial:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"total_bill\", y=\"day\", hue=\"time\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "This approach uses the kernel density estimate to provide a better description of the distribution of values. Additionally, the quartile and whikser values from the boxplot are shown inside the violin. Because the violinplot uses a KDE, there are some other parameters that may need tweaking, adding some complexity relative to the straightforward boxplot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"total_bill\", y=\"day\", hue=\"time\", data=tips,\n",
    "               bw=.1, scale=\"count\", scale_hue=False);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It's also possible to \"split\" the violins when the hue parameter has only two levels, which can allow for a more efficient use of space:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips, split=True);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Finally, there are several options for the plot that is drawn on the interior of the violins, including ways to show each individual observation instead of the summary boxplot values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips,\n",
    "               split=True, inner=\"stick\", palette=\"Set3\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It can also be useful to combine :func:`swarmplot` or :func:`swarmplot` with :func:`violinplot` or :func:`boxplot` to show each observation along with a summary of the distribution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=\"day\", y=\"total_bill\", data=tips, inner=None)\n",
    "sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips, color=\"w\", alpha=.5);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Statistical estimation within categories\n",
    "----------------------------------------\n",
    "\n",
    "Often, rather than showing the distribution within each category, you might want to show the central tendency of the values. Seaborn has two main ways to show this information, but importantly, the basic API for these functions is identical to that for the ones discussed above.\n",
    "\n",
    "Bar plots\n",
    "^^^^^^^^^\n",
    "\n",
    "A familiar style of plot that accomplishes this goal is a bar plot. In seaborn, the :func:`barplot` function operates on a full dataset and shows an arbitrary estimate, using the mean by default. When there are multiple observations in each category, it also uses bootstrapping to compute a confidence interval around the estimate and plots that using error bars:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=\"sex\", y=\"survived\", hue=\"class\", data=titanic);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "A special case for the bar plot is when you want to show the number of observations in each category rather than computing a statistic for a second variable. This is similar to a histogram over a categorical, rather than quantitative, variable. In seaborn, it's easy to do so with the :func:`countplot` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.countplot(x=\"deck\", data=titanic, palette=\"Greens_d\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Both :func:`barplot` and :func:`countplot` can be invoked with all of the options discussed above, along with others that are demonstrated in the detailed documentation for each function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.countplot(y=\"deck\", hue=\"class\", data=titanic, palette=\"Greens_d\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Point plots\n",
    "^^^^^^^^^^^\n",
    "\n",
    "An alternative style for visualizing the same information is offered by the :func:`pointplot` function. This function also encodes the value of the estimate with height on the other axis, but rather than show a full bar it just plots the point estimate and confidence interval. Additionally, :func:`pointplot` connects points from the same ``hue`` category. This makes it easy to see how the main relationship is changing as a function of a second variable, because your eyes are quite good at picking up on differences of slopes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.pointplot(x=\"sex\", y=\"survived\", hue=\"class\", data=titanic);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "To make figures that reproduce well in black and white, it can be good to use different markers and line styles for the levels of the ``hue`` category:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.pointplot(x=\"class\", y=\"survived\", hue=\"sex\", data=titanic,\n",
    "              palette={\"male\": \"g\", \"female\": \"m\"},\n",
    "              markers=[\"^\", \"o\"], linestyles=[\"-\", \"--\"]);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Plotting \"wide-form\" data\n",
    "-------------------------\n",
    "\n",
    "While using \"long-form\" or \"tidy\" data is preferred, these functions can also by applied to \"wide-form\" data in a variety of formats, including pandas DataFrames or two-dimensional numpy arrays. These objects should be passed directly to the ``data`` parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(data=iris, orient=\"h\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Additionally, these functions accept vectors of Pandas or numpy objects rather than variables in a ``DataFrame``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x=iris.species, y=iris.sepal_length);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "To control the size and shape of plots made by the functions discussed above, you must set up the figure yourself using matplotlib commands. Of course, this also means that the plots can happily coexist in a multi-panel figure with other kinds of plots:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f, ax = plt.subplots(figsize=(7, 3))\n",
    "sns.countplot(y=\"deck\", data=titanic, color=\"c\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Drawing multi-panel categorical plots\n",
    "-------------------------------------\n",
    "\n",
    "As we mentioned above, there are two ways to draw categorical plots in seaborn. Similar to the duality in the regression plots, you can either use the functions introduced above, or the higher-level function :func:`factorplot`, which combines these functions with a :func:`FacetGrid` to add the ability to examine additional categories through the larger structure of the figure. By default, :func:`factorplot` produces a :func:`pointplot`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=tips);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "However, the ``kind`` parameter lets you chose any of the kinds of plots discussed above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=tips, kind=\"bar\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "The main advantage of using a :func:`factorplot` is that it is very easy to \"facet\" the plot and investigate the role of other categorical variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n",
    "               col=\"time\", data=tips, kind=\"swarm\");"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Any kind of plot can be drawn. Because of the way :class:`FacetGrid` works, to change the size and shape of the figure you need to specify the ``size`` and ``aspect`` arguments, which apply to each facet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.factorplot(x=\"time\", y=\"total_bill\", hue=\"smoker\",\n",
    "               col=\"day\", data=tips, kind=\"box\", size=4, aspect=.5);"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "It is important to note that you could also make this plot by using :func:`boxplot` and :class:`FacetGrid` directly. However, special care must be taken to ensure that the order of the categorical variables is enforced in each facet, either by using data with a ``Categorical`` datatype or by passing ``order`` and ``hue_order``.\n",
    "\n",
    "Because of the generalized API of the categorical plots, they should be easy to apply to other more complex contexts. For example, they are easily combined with a :class:`PairGrid` to show categorical relationships across several different variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.PairGrid(tips,\n",
    "                 x_vars=[\"smoker\", \"time\", \"sex\"],\n",
    "                 y_vars=[\"total_bill\", \"tip\"],\n",
    "                 aspect=.75, size=3.5)\n",
    "g.map(sns.violinplot, palette=\"pastel\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6  (seaborn-dev)",
   "language": "python",
   "name": "seaborn-dev"
  },
  "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}

{'fraction_non_alphanumeric': 0.17191091776454012, 'fraction_numerical': 0.0010875744617742293, 'mean_word_length': 3.1593502621568827, 'pattern_counts': {'":': 536, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4601086', 'n_tokens_mistral': 12834, 'n_tokens_neox': 12437, 'n_words': 4182}