Data Visualization Tutorial Using Seaborn | by Pavan Kumar Boinapalli | Towards Data Science

“Seaborn makes the exploratory data analysis phase of your data science project beautiful and painless”
This tutorial is targeted at the audience who have worked with Seaborn, but had lost the touch of it. I hope that, by reading this article, you can recollect Seaborn visualization style and commands to get started with your data exploration. This tutorial layout is such that, it shows how and what visualizations you can do using Seaborn, given you have x number of numerical features and y number of categorical features.
Lets import Seaborn:
import seaborn as sns
We will be using the tips dataset available within the seaborn library.
Load the dataset using:
tips = sns.load_dataset('tips')
total_bill(numerical variable) : Total bill for the tabletip(Numeric): Tip for the waiter serving the table sex (Categorical): Gender of the bill payer (Male/Female)smoker(Categorical): Whether the bill payer was a smoker (Yes/No)day(Categorical): Day of the week (Sun, Mon... etc)table_size(Numerical) : Capacity of the tabledate: date and time of the bill payment
Let’s start with different styles available in Seaborn. Each style is differentiated by background colour, grid layout and axis ticks of the plot. There are five basic styles available in Seaborn: Dark, Darkgrid, White, White Grid and Ticks.
sns.set_style('dark')sns.set_style('darkgrid')sns.set_style('ticks')sns.set_style('white')sns.set_style('whitegrid')
Let’s look at various visualizations we can do using Seaborn. Each segment below shows how to perform visualizations given the number of categorical and numerical variables that are available to you.
If we have one numerical variable, we can analyse the distribution of that variable.
g = sns.distplot(tips.tip)g.set_title('Tip Amount Distribution');g = sns.distplot(tips.tip,kde=False)g.set_title('Tip Amount Histogram');g = sns.distplot(tips.tip,rug=True)g.set_title('Tip Amount Distribution with rug');
We can observe that the tip amount data is approximately normal.
If we have one categorical variable, we can do a count plot which shows frequency of occurrence of each value of the categorical variable.
g = sns.catplot(x="day",kind='count',order=['Thur','Fri','Sun','Sat'],data=tips);g.fig.suptitle("Frequency of days in the tips dataset [Count Plot]",y=1.05);
To analyse relationship between two numerical variables, we can do scatter plots in seaborn.
g = sns.relplot(x="total_bill",y="tip",data=tips,kind='scatter');g.fig.suptitle('Relationship between continuous variables [Scatter Plot]',y=1.05);
Seaborn also makes it easy to visualize density distribution of the relationship between two numerical variables.
g = sns.jointplot(x="total_bill",y='tip',data=tips,kind='kde');g.fig.suptitle('Density distribution among tips and total_bill [Joint Plot]',y=1.05);
kde plot is another plot to visualize the distribution of relationship between two continuous variables.
g = sns.jointplot(x="total_bill",y='tip',data=tips,kind='kde');g.fig.suptitle('Density distribution among tips and total_bill [Joint Plot]',y=1.05);
We can also plot a regression line with confidence intervals with one numerical variable as dependent variable and other as independent variable.
g = sns.lmplot(x="total_bill",y="tip",data=tips);g.fig.suptitle('Relationship b/w tip and total_bill [Scatter Plot + Regression Line]',y=1.05);
If the independent variable is datetime, we can do a lineplot, which is also a timeseries plot.
g = sns.lineplot(x="date",y="total_bill",data=tips);g.set_title('Total bill amount over time [Line plot]');
With two numerical variables and one categorical variable, we can do all the plots mentioned in the two numerical variables section . The additional dimension of categorical variable can be used as a colour/marker to distinguish the categorical variable values in the plot.
g = sns.relplot(x="total_bill",y="tip",hue='sex',kind='scatter',data=tips);g.fig.suptitle('Relationship b/w totalbill and tip distinguished by gender [Scatter Plot]',y=1.05);g = sns.relplot(x="total_bill",y="tip",style='sex',kind='scatter',data=tips)g.fig.suptitle('Relationship b/w totalbill distinguished by gender as marker [Scatter Plot]',y=1.05);
Alternatively, we can use each categorical variable value as a group to plot relationship between two numerical variables for each categorical variable value.
g = sns.relplot(x="total_bill",y="tip",col='sex',kind='scatter',data=tips);g.fig.suptitle('Relationship between totalbill and tip by gender [Scatter Plot]',y=1.05);
If we have three numerical variables, we can do a scatter plot for two variables and third variables can be used as size of the points in the scatter plot.
g = sns.relplot(x="total_bill",y="tip",size='table_size',kind='scatter',data=tips);g.fig.suptitle('total bill vs tip distinguished by table size [Scatter Plot]',y=1.05);
If we have three numerical and one categorical variable, the same plot mentioned in the above section can be plotted for each value of the categorical variable.
g = sns.relplot(x="total_bill",y="tip",col='sex',size='table_size',kind='scatter',data=tips);g.fig.suptitle('Total bill vs tip by gender distinguished by table size [Scatter Plot]',y=1.03);
This is probably the most basic, common and useful plot in data visualization. If we have one numerical variable and one categorical variable, we can do various plots like bar plot and strip plot.
g = sns.catplot(x="day",y="tip",kind='bar',order=['Thur','Fri','Sun','Sat'],ci=False,data=tips);g.fig.suptitle('Tip amount by day of week [Bar Plot]',y=1.05);
g = sns.catplot(x="day",y="tip",kind='strip',order=['Thur','Fri','Sun','Sat'],ci=False,data=tips);g.fig.suptitle('Tip amount by day along with tips as scatter [Strip Plot]',y=1.03);
The swarm plot and violin plot as shown below allow us to visualization of distribution of numerical variable within each categorical variable.
g = sns.catplot(x="day",y="tip",kind='swarm',order=['Thur','Fri','Sun','Sat'],ci=False,data=tips);g.fig.suptitle('Tip amount by day along with tip distribution [Swarm Plot]',y=1.05);
g = sns.catplot(x="day",y="tip",kind='violin',order=['Thur','Fri','Sun','Sat'],data=tips);g.fig.suptitle('Tips distributions by day [Violin Plot]');
We can visualize the Inter Quartile Range(25th percentile to 75th percentile) of continuous variable within each value of categorical variable using a point plot.
g = sns.catplot(x="day",y="tip",kind='point',order=['Thur','Fri','Sun','Sat'],data=tips,capsize=0.5);g.fig.suptitle('IQR Range of tip by day [Point Plot]',y=1.05);
With one numerical and two categorical variables, we can use all the plots mentioned in the above section and accommodate the additional third categorical variable either as a column variable or as a subgroup in each subplot as shown below.
g = sns.catplot(x="day",y="tip",kind='bar',col='smoker',order=['Thur','Fri','Sun','Sat'],ci=False,data=tips);g.fig.suptitle('Tip amount by day of week by smoker/non-smoker [Bar Plot]',y=1.05);
g = sns.catplot(x="day",y="tip",kind='bar',hue='smoker',order=['Thur','Fri','Sun','Sat'],ci=False,data=tips);g.fig.suptitle('Tips by day with smoker/non-smoker subgroup [Grouped Bar Plot]',y=1.05);
With one numerical and three categorical, we can do all the visualizations mentioned in the one categorical and one numerical variable section and accommodate additional two categorical variables with one variable as a column variable/ row variable of the figure and other as a sub group in each sub plot.
g = sns.catplot(x="day",y="tip",kind='bar',hue='smoker',col='sex',order=['Thur','Fri','Sun','Sat'],ci=False,data=tips);g.fig.suptitle('Tips by day with smoker/non-smoker subgroup by gender [Grouped Bar Plot]',y=1.05);
Finally, If we have more than three numerical variables, we can use heat map or pariplot. With these plots, we visaualize relationship between each and every other numerical variable in a single plot.
g = sns.heatmap(tips.corr());g.set_title('correlation between continuous variables [Heat Map]');
g = sns.pairplot(tips);g.fig.suptitle('Relationship between continuous variables [Patiplot]',y=1.03);
Some Seaborn plots return matplotlib AxesSubplot while others return FacetGrid (If you forgot what are matplotlib AxesSubplots, check my notes on matplotlib for reference).
The FacetGrid is a grid(2D Array) of matplotlib AxesSubPlots. You can access each subplot using array indices and set labels, titles for each plot.
g = sns.relplot(x="total_bill",y="tip",data=tips,kind='scatter');g.axes[0,0].set_title('Relationship between continuous variables [Scatter Plot]');g.axes[0,0].set_xlabel('Total Bill Amount');g.axes[0,0].set_ylabel('Tip Amount');
If the plot returns AxesSubplot, you can use AxesSubplot methods to set titles and legends.
g = sns.distplot(tips.tip)g.set_title('Tip Amount Probablity Distribution');g.set_xlabel('Tip Amount')g.set_ylabel('probability')
For FacetGrid, you can get figure object from the FacetGrid object and set title for the figure object.
g = sns.relplot(x="total_bill",y="tip",col='sex',kind='scatter',data=tips);g.fig.suptitle('Relationship between totalbill and tip by gender [Scatter Plot]',y=1.05);
Hopefully, you find this tutorial helpful in getting started with making beautiful visualizations, easily with seaborn. Although Seaborn is easy to use, it also offers a lot of customisation, which is an advanced topic. Once you are comfortable with basic plots, you can explore Seaborn further as you use it for your visualizations.
The data set used for displaying sample plots:https://github.com/mwaskom/seaborn-data/blob/master/tips.csv
Official Seaborn website:https://seaborn.pydata.org/
Source code to plots used in this article are available in my github repo:https://github.com/pavankumarboinapalli/articles/blob/master/seabornify.ipynb
I am open to constructive criticism. Please feel free to comment about ways to improve this article. For example, if you feel there is some information that can be included or if you want more explanation on a sub-topic.