Seaborn FacetGrid: Taking Subplots Further | by Soner Yıldırım | Towards Data Science

Data visualizations are essential in data analysis. The famous saying “one picture is worth a thousand words” holds true in the scope of data visualizations as well. In this post, I will explain a well-structured, very informative collection of subplots: FacetGrid.
FacetGrid is basically a grid of subplots. Matplotlib supports creating figures with multiple axes and thus allows to have subplots in one figure. What FacetGrid puts on top of matplotlib’s subplot structure:
Making the process easier and smoother (with less code)
Transfering the structure of dataset to subplots
The distribution of a variable or relationship among variables can easily be discovered with FacetGrids. They can have up to three dimensions: row, column, and hue. It will be more clear as we go through examples. So, let’s start.
As always we start with importing libraries.
Note: FacetGrid requires the data stored in a pandas dataframe where each row represents an observation and columns represent variables. Thus, we also import pandas.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='darkgrid', color_codes=True)%matplotlib inline
We will use the built-in “tips” dataset of seaborn.
tip = sns.load_dataset("tips")tip.head()
FacetGrid object is initialized by passing a dataframe and name of variables to create the structure of axes. The variables used to initialize FacetGrid object needs to be categorical or discrete. The grid structure is created according to the number of categories. For instance, “time” column has two unique values.
tip['time'].value_counts()Dinner    176 Lunch      68 Name: time, dtype: int64
Let’s initialize a FacetGrid object by passing “time” variable to col parameter.
g = sns.FacetGrid(tip, col='time')
We’ve just created a very simple grid with two facets (each subplot is a facet). The size of facets are adjusted using height and aspect parameters.
Height is the height of facets in inches
Aspect is the ratio of width and height (width=aspect*height). Default value of aspect is 1.
Let’s update the grid with larger facets.
g = sns.FacetGrid(tip, col='time', height=5)
It is time to plot data on the grid using FacetGrid.map() method. It takes a plotting function and variable(s) to plot as arguments.
g = sns.FacetGrid(tip, col='time', height=5)g.map(plt.hist, "total_bill")
The grid shows histogram of “total_bill” based on “time”. Depending on the plotting function, we may need to pass multiple variables for map method. For instance, scatter plots require two variables.
g = sns.FacetGrid(tip, col='time', height=5)g.map(plt.scatter, "total_bill", "tip")
Let’s add one more dimension to the grid with row parameter.
g = sns.FacetGrid(tip, row='sex', col='time', height=4)g.map(plt.scatter, "total_bill", "tip")
Both “sex” and “time” columns have two distinct values so a 2x2 FacetGrid is created. As we can see from the plot above, “total_bill” and “tip” variables have a similar trend for males and females.
The hue parameter allows to add one more dimension to the grid with colors.
g = sns.FacetGrid(tip, row='sex', col='time', hue='smoker',                      height=4)g.map(plt.scatter, "total_bill", "tip")g.add_legend()
We now have an overview of the relationship among “total_bill”, “tip”, and “smoker” variables.
The “day” column has 4 unique values:
tip.day.value_counts()Sat     87 Sun     76 Thur    62 Fri     19 Name: day, dtype: int64
We can create a FacetGrid that shows the distribution of “total_bill” in different days. It will show if customers spend more on any particular day.
g = sns.FacetGrid(tip, row='day',                   row_order = tip.day.value_counts().index,                  height=1.5, aspect=4)g.map(sns.distplot, "total_bill", hist=False)
It seems like people tend to spend a little more on the weekend. We have used row_order parameter for this plot. As the name suggests, it determines the order of facets. In the previous plots, we used plotting functions from matplotlib.pyplot interface. But, for the last one, we used a plotting function from seaborn package. It is a nice feature of FacetGrid that provides additional flexibility.
There are many more features that can be added on FacetGrids in order to enrich both the functionality and appearance of them. If you want to go deeper, I suggest going over seaborn documentation on FacetGrid.
Thank you for reading. Please let me know if you have any feedback.