9 Examples to Master Seaborn Grids | by Soner Yıldırım | Towards Data Science

Data visualization is a fundamental piece of data analysis. It helps us better understand the relationships in the data and explore the underlying structure.
We can create more informative visualizations by combining multiple plots in the same figure. There are many ways to create multi-plot visualizations. Seaborn library makes it simple and straightforward to generate such plots using the FacetGrid and PairGrid classes.
In this article, we will go over 9 examples to practice how to use these function. We will start with very basic ones and steadily increase the complexity. For the examples, we will be using a customer churn dataset available on Kaggle.
We start with importing the necessary libraries.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='darkgrid')
The next step is to read the dataset into a Pandas dataframe.
cols = [        'Attrition_Flag','Gender','Education_Level',        'Marital_Status','Customer_Age','Credit_Limit',        'Total_Trans_Amt','Avg_Open_To_Buy'       ]churn = pd.read_csv(    "/content/BankChurners.csv", usecols=cols    ).sample(n=1000)churn = churn[churn.Marital_Status.isin(['Married','Single'])]churn = churn[churn.Education_Level.isin(['Graduate','High School', 'Unknown'])]churn.head()
I have selected some of the columns in the original dataset and also done some filtering and sampling for demonstration purposes.
FacetGrid is a grid of subplots which allows for transferring the structure of the dataset to the subplots. Row, col, and hue parameters can be considered as the three dimensions of FacetGrid objects.
We first create a FacetGrid object and then map the data. Let’s start with a very simple example of creating the structure of a FacetGrid.
g = sns.FacetGrid(churn, col='Attrition_Flag', height=4, aspect=1.2)
We now have an empty plot that only represents the structure. Seaborn generates the structure based on the values in the columns passed to the col and row parameters. Since the attrition flag column has two unique values, a grid with two columns is returned.
The height and aspect parameters adjust the size of subplots.
Once we have a FacetGrid object, we can map data to it.
g = sns.FacetGrid(churn, col='Attrition_Flag', height=4, aspect=1.2)g.map(sns.histplot, 'Customer_Age')
The map method takes a plotting function and variables to plot as argument. The grid above shows the distribution of the customer age column using a histogram. The data points are separated according to the categories in attrition flag column.
The plotting function passed to the map method does not have to be a Seaborn function. We can also use matplotlib functions. For instance, the plot above can be created with “plt.hist”.
g = sns.FacetGrid(churn, col='Attrition_Flag', height=4, aspect=1.2)g.map(plt.hist, 'Customer_Age')
Note: Seaborn also accepts custom functions to use for mapping. However, there are certain rules you must follow when creating them.
We have only used the col parameter so far. We can use the row and hue parameters to add more dimensions.
g = sns.FacetGrid(   churn, row='Attrition_Flag', col='Gender', hue='Marital_Status',    height=4, aspect=1.4)g.map(sns.scatterplot, 'Total_Trans_Amt', 'Avg_Open_To_Buy')g.add_legend()
We have a grid of scatter plots that show the relationship between two numerical columns. We are able to demonstrate relationship separately for categories in the attrition flag, gender, and marital status columns.
When we use the hue parameter, the legend should also be added using the add_legend function.
We can specify the order of the categories represented by the subplots. The row_order and col_order parameters can be used to order.
col_order = churn.Education_Level.value_counts().indexg = sns.FacetGrid(   churn, col='Education_Level', height=4,   col_order = col_order)g.map(sns.histplot, 'Total_Trans_Amt')
As you can also notice from the plots, the categories are sorted by size. We have used the value_counts function of Pandas to generate an order for the categories.
PairGrid generates a grid of plots that visualize the pairwise relationships of variables. For instance, we can create a grid of scatter plots between some numerical variables.
cols = ['Credit_Limit','Total_Trans_Amt','Customer_Age']g = sns.PairGrid(churn[cols], height=3.5)g.map(sns.scatterplot)
In the previous example, the plots on the diagonal are useless because they show a scatter plot of a variable with itself. In order to make the grid more informative, we can plot histograms of variables on the diagonal.
We pass separate functions by using the map_diag and map_offdiag methods.
g = sns.PairGrid(churn[cols], height=3)g.map_diag(sns.histplot)g.map_offdiag(sns.scatterplot)
It is better than the previous one as we also get an overview of the distribution of each variable.
The PairGrid also supports the hue parameter so we can separate the data points in the scatter plot based on a categorical variable.
Another useful parameter is the var parameter. In the previous examples for PairGrid, we used a subset of the dataframe so it only included the columns to be plotted. We can also pass a list of columns to be plotted to the var parameter.
g = sns.PairGrid(churn, vars=cols, hue='Attrition_Flag', height=3)g.map_diag(sns.histplot)g.map_offdiag(sns.scatterplot)g.add_legend()
In a PairGrid, the plots on the upper and lower side of diagonal are mirror images. Thus, we have the same plot from a different perspective.
We have the option to have different kind of plots on the upper and lower side of the diagonal. The map_upper and map_lower functions are used to generate different kinds of plots for the upper and lower side.
g = sns.PairGrid(churn, vars=cols, height=3)g.map_diag(sns.histplot)g.map_upper(sns.scatterplot)g.map_lower(sns.histplot)
On the upper side, we have the scatter plots. The diagonal contains the histograms of each variable. On the lower side, we have two-dimensional histograms.
We have practiced how to create multi-plot visualizations with the FacetGrid and PairGrid of Seaborn. They are very useful tools for exploratory data analysis. The way Seaborn generates these plots makes them simple and easy to understand.
It is important to understand the differences between a FacetGrid and PairGrid. In a FacetGrid, each subplot represents the same relationship but under different conditions. For instance, we can have a scatter plot of two variables in a FacetGrid and separate the data points based on the categories of another variables.
In the PairGrid, each plot shows a different relationship. For instance, when we create a PairGrid of scatter plots with three variables, each subplot represents a different pairwise relationship.
There are many more features that can be added on FacetGrid and PairGrid objects in order to enrich both the functionality and appearance. Once you are comfortable with the basic ones, you can create more detailed grids.
Thank you for reading. Please let me know if you have any feedback.