.. _categorical_tutorial: .. currentmodule:: seaborn

# Plotting with categorical data

We :ref:`previously ` 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. 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. 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. It is easiest and best to invoke these functions with a DataFrame that is in `"tidy" `_ format, although the lower-level functions also accept wide-form DataFrames or simple vectors of observations. See below for examples.
``````

In [ ]:

%matplotlib inline

``````
``````

In [ ]:

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

``````
``````

In [ ]:

import seaborn as sns
sns.set(style="whitegrid", color_codes=True)

``````
``````

In [ ]:

np.random.seed(sum(map(ord, "categorical")))

``````
``````

In [ ]:

``````
Categorical scatterplots ------------------------ 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:
``````

In [ ]:

sns.stripplot(x="day", y="total_bill", data=tips);

``````
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":
``````

In [ ]:

sns.stripplot(x="day", y="total_bill", data=tips, jitter=True);

``````
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:
``````

In [ ]:

sns.swarmplot(x="day", y="total_bill", data=tips);

``````
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:
``````

In [ ]:

sns.swarmplot(x="day", y="total_bill", hue="sex", data=tips);

``````
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:
``````

In [ ]:

sns.swarmplot(x="size", y="total_bill", data=tips);

``````
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``:
``````

In [ ]:

sns.swarmplot(x="total_bill", y="day", hue="time", data=tips);

``````
Distributions of observations within categories ----------------------------------------------- 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 ` to the case where we want to quickly compare across several distributions. Boxplots ^^^^^^^^ 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:
``````

In [ ]:

sns.boxplot(x="day", y="total_bill", hue="time", data=tips);

``````
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:
``````

In [ ]:

tips["weekend"] = tips["day"].isin(["Sat", "Sun"])
sns.boxplot(x="day", y="total_bill", hue="weekend", data=tips, dodge=False);

``````
Violinplots ^^^^^^^^^^^ A different approach is a :func:`violinplot`, which combines a boxplot with the kernel density estimation procedure described in the :ref:`distributions ` tutorial:
``````

In [ ]:

sns.violinplot(x="total_bill", y="day", hue="time", data=tips);

``````
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:
``````

In [ ]:

sns.violinplot(x="total_bill", y="day", hue="time", data=tips,
bw=.1, scale="count", scale_hue=False);

``````
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:
``````

In [ ]:

sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True);

``````
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:
``````

In [ ]:

sns.violinplot(x="day", y="total_bill", hue="sex", data=tips,
split=True, inner="stick", palette="Set3");

``````
It can also be useful to combine :func:`swarmplot` or :func:`striplot` with :func:`violinplot` or :func:`boxplot` to show each observation along with a summary of the distribution:
``````

In [ ]:

sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5);

``````
Statistical estimation within categories ---------------------------------------- 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. Bar plots ^^^^^^^^^ 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:
``````

In [ ]:

sns.barplot(x="sex", y="survived", hue="class", data=titanic);

``````
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:
``````

In [ ]:

sns.countplot(x="deck", data=titanic, palette="Greens_d");

``````
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:
``````

In [ ]:

sns.countplot(y="deck", hue="class", data=titanic, palette="Greens_d");

``````
Point plots ^^^^^^^^^^^ 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:
``````

In [ ]:

sns.pointplot(x="sex", y="survived", hue="class", data=titanic);

``````
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:
``````

In [ ]:

sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
palette={"male": "g", "female": "m"},
markers=["^", "o"], linestyles=["-", "--"]);

``````
Plotting "wide-form" data ------------------------- 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:
``````

In [ ]:

sns.boxplot(data=iris, orient="h");

``````
Additionally, these functions accept vectors of Pandas or numpy objects rather than variables in a ``DataFrame``:
``````

In [ ]:

sns.violinplot(x=iris.species, y=iris.sepal_length);

``````
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:
``````

In [ ]:

f, ax = plt.subplots(figsize=(7, 3))
sns.countplot(y="deck", data=titanic, color="c");

``````
Drawing multi-panel categorical plots ------------------------------------- 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`:
``````

In [ ]:

sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips);

``````
However, the ``kind`` parameter lets you chose any of the kinds of plots discussed above:
``````

In [ ]:

sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar");

``````
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:
``````

In [ ]:

sns.factorplot(x="day", y="total_bill", hue="smoker",
col="time", data=tips, kind="swarm");

``````
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:
``````

In [ ]:

sns.factorplot(x="time", y="total_bill", hue="smoker",
col="day", data=tips, kind="box", height=4, aspect=.5);

``````
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``. 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:
``````

In [ ]:

g = sns.PairGrid(tips,
x_vars=["smoker", "time", "sex"],
y_vars=["total_bill", "tip"],
aspect=.75, height=3.5)
g.map(sns.violinplot, palette="pastel");

``````
``````

In [ ]:

``````