10 Data Visualizations using Seaborn for Data Scientists
By: Saurav Anand
Tags: Artificial Intelligence, Machine Learning, Data Analytics, Data Visualization, Data Science

In good information visualizations, there are no rules , no guidelines , no templates, no standard technologies , no style books … You must simply do whatever it takes — Edward Tufte

Introduction

Seaborn provides a high-level interface to Matplotlib, a powerful but sometimes unwieldy Python visualization library.On Seaborn’s official website, they state:

If matplotlib “tries to make easy things easy and hard things possible”, seaborn tries to make a well-defined set of hard things easy too.

Features of Seaborn :

Using default themes that are aesthetically pleasing.

Setting custom color palettes.

Making attractive statistical plots.

Easily and flexibly displaying distributions.

Visualizing information from matrices and DataFrames.

Those last three points are why Seaborn is our tool of choice for Exploratory Analysis. It makes it very easy to “get to know” your data quickly and efficiently.

Seaborn vs Matplotlib

It is summarized that if Matplotlib “tries to make easy things easy and hard things possible”, Seaborn tries to make a well-defined set of hard things easy too.”

Seaborn helps resolve the two major problems faced by Matplotlib; the problems are −

Default Matplotlib parameters

Working with data frames

As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If we know Matplotlib, we are already half way through Seaborn. Please have a look at this article which states the various visualization techniques in matplotlib :

Let’s look at the 10 cool visualization techniques which every data scientists and data analyst should know :-

1.Rel Plot

It is very much important to understand the relationship between different variables and how this relationship is statistically significant. Rel Plot helps us in finding out this .

Seaborn relplot() function helps us to draw figure-level interface for drawing relational plots onto a FacetGrid.

function helps us to draw figure-level interface for drawing relational plots onto a FacetGrid. This function provides access to several different axes-level functions that show the relationship between two variables with semantic mappings of subsets.

The kind parameter selects the underlying axes-level function to use-

parameter selects the underlying axes-level function to use- scatterplot() (with kind=”scatter”; the default)

lineplot() (with kind=”line”)

# Drawing scatter plot using relplot

plt.figure(figsize=(14,16))

sns.relplot(x="wheel-base" , y="engine-size" , hue="num-of-cylinders" ,kind='scatter', height=8.5,aspect =1,data=auto)

plt.show()

# Facet along the columns and rows to show a categorical variable using "col" and "row" par

sns.set(rc={'xtick.labelsize':12,'ytick.labelsize':12,'axes.labelsize':12})

sns.relplot(x="wheel-base", y="engine-size", hue="fuel-type",col="fuel-type", row="body-style", data=auto)

plt.show()

# Combining lineplots using relplot



plt.figure(figsize=(10,10))

sns.set(rc={'xtick.labelsize':17,'ytick.labelsize':17,'axes.labelsize':20 , "axes.grid":False})

sns.relplot(x="wheel-base" , y="engine-size" , hue="num-of-cylinders" , col="fuel-type",kind='line', height=8.5,data=auto)

plt.show()

2.Cat plot

Cat Plot provides access to several axes-level functions (“point”, “bar”, “strip”, “swarm”,”box”, “violin”, “count” or “boxen”) that show the relationship between a numerical and one or more categorical variables.

We can use Seaborn Catplot() function to plot categorical scatterplots.

function to plot categorical scatterplots. The default representation of the data in catplot() uses a scatterplot.

uses a scatterplot. It helps to draw figure-level interface for drawing categorical plots onto a facetGrid.

This function provides access to several axes-level functions that show the relationship between a numerical and one or more categorical variables using one of several visual representations.

The kind parameter selects the underlying axes-level function to use.

# Use Count Plot to visualize data

plt.figure(figsize=(10,10))

sns.catplot(y ='body-style', kind = "count",data = auto)

plt.show()

# Use Voilin Plot to visualize data

plt.figure(figsize=(12,10))

sns.catplot(x="body-style" , y = "city-mpg" ,kind="violin" ,data=auto)

plt.show()

# Facet along the columns to show a categorical variable using "col" parameter

plt.figure(figsize=(10,10))

sns.catplot(x='body-style' , y='city-mpg' , data=auto , col="fuel-type")

plt.show()

""" Facet along the columns to show a categorical variable using "col" parameter and

Limiting the number of columns using "col_wrap" """

plt.figure(figsize=(20,10))

sns.catplot("fuel-type", col="body-style",col_wrap=2,data=auto,kind="count",height=5, aspect=1)

plt.show()

# Facet along the columns to show a categorical variable using "col" parameter

sns.set(rc={'xtick.labelsize':10,'ytick.labelsize':10,'axes.labelsize':14})

sns.set_style("white")

sns.catplot(x="fuel-type" , y = "engine-size" , col= "body-style" , data=auto, kind="swarm" , height=5,aspect=0.5)

plt.show()

# Facet along the columns to show a categorical variable using "col" parameter

plt.figure(figsize=(11,9))

sns.catplot(x="body-style" , y = "engine-size", col="fuel-type", kind="violin",palette="Set2" , height= 7,scale = "count",data=auto)

plt.show()

# Facet along the columns to show a categorical variable using "col" parameter

plt.figure(figsize=(11,9))

sns.catplot(x="body-style" , y = "engine-size", col="fuel-type", kind="strip",palette="Set1" , height=10,data=auto)

plt.show()

# Facet along the columns to show a categorical variable using "col" parameter

plt.figure(figsize=(11,9))

sns.catplot(x="body-style" , y = "engine-size", col="fuel-type", kind="boxen",palette="Set2" , height=7,data=auto)

plt.show()

3.KDE Plot

KDE Plot is used to estimate the probability density function of a continuous random variable.

The kernel density estimate (KDE) plot is a useful tool for plotting the shape of a distribution.

plot is a useful tool for plotting the shape of a distribution. Seaborn kdeplot is another seaborn plotting function that fits and plot a univariate or bivariate kernel density estimate.

Like the histogram, the KDE plots encode the density of observations on one axis with height along the other axis.

We can plot a KDE plot as follows-

sns.set_style("darkgrid")

fig1 , axes = plt.subplots(nrows=2,ncols=2 , figsize = (14,14))

x = np.random.normal(1,10,1000)

#Simple KDE Plot

axes[0,0].set_title("Simple KDE Plot")

sns.kdeplot(x,ax=axes[0,0])

# Shade under the density curve using the "shade" parameter

axes[0,1].set_title("KDE Plot (Shaded Area Under the Curve)")

sns.kdeplot(x,shade=True,ax=axes[0,1])

# Shade under the density curve using the "shade" parameter and use a different color.

axes[1,0].set_title("KDE Plot (Different Color)")

sns.kdeplot(x,ax=axes[1,0],color = 'r',shade=True,cut=0)

#Plotting the density on the vertical axis

axes[1,1].set_title("KDE Plot (Density on Vertical Axis)")

sns.kdeplot(x,vertical=True)

plt.show()

plt.figure(figsize=(6,8))

x = np.linspace(0, 10, 100)

y = np.sin(x)

sns.kdeplot(x,y,shade=True,cmap="Reds", shade_lowest=False)

4.Swarm Plot

It draw a categorical scatterplot with non-overlapping points.A swarm plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution.

#Simple Swarm plot

plt.figure(figsize=(10,10))

sns.swarmplot(auto['fuel-type'], auto['city-mpg'])

plt.show()

# Draw horizontal swarm plot

plt.figure(figsize=(10,10))

sns.swarmplot(auto['city-mpg'], auto['fuel-type'])

plt.show()

# Defining the size of the plots

plt.figure(figsize=(7,7))

sns.swarmplot(auto['fuel-type'], auto['city-mpg'], size=10)

plt.show()

# Displaying multiple swarmplots using subplot function.

fig1 , axes = plt.subplots(nrows=2,ncols=2 , figsize = (20,20))

sns.swarmplot(auto['fuel-type'], auto['city-mpg'], ax = axes[0,0], size=8)

sns.swarmplot(auto['fuel-type'] , auto['wheel-base'] ,ax = axes[0,1], size=8)

sns.swarmplot(auto['fuel-type'] ,auto['length'] , ax = axes[1,0] , size=8)

sns.swarmplot(auto['fuel-type'] , auto['width'] , ax = axes[1,1] , size=8)

plt.show()

#Changing edge color , size and linewidth of data points

plt.figure(figsize=(7,7))

sns.swarmplot(x= "fuel-type", y = "wheel-base", size = 9 , linewidth= 2 , edgecolor="black" , data =auto)

plt.show()

# Show groups with different colors using "hue"

plt.figure(figsize=(7,7))

sns.swarmplot(x= "engine-location", y = "engine-size", hue="fuel-type", size = 8 , data = auto)

# Facet along the columns to show a categorical variable using "col" parameter

sns.set(rc={'xtick.labelsize':10,'ytick.labelsize':10,'axes.labelsize':14})

sns.set_style("white")

sns.catplot(x="fuel-type" , y = "engine-size" , col= "body-style" , data=auto, kind="swarm" , height=5,aspect=0.5)

plt.show()

5.Boxen Plot

The Boxen Plot shows a large number of quantiles. By plotting more quantiles, it provides more information about the shape of the distribution, particularly in the tails. It is similar to a box plot in plotting a non-parametric representation of a distribution in which all features correspond to actual observations. By plotting more quantiles, it provides more information about the shape of the distribution, particularly in the tails.

# Simple Boxen Plot

plt.figure(figsize=(8,7))

sns.boxenplot(y=auto["engine-size"])

plt.show()

plt.figure(figsize=(7,9))

sns.boxenplot(x=auto["fuel-type"] , y = auto["engine-size"] ,palette="Set1")

plt.show()

# Drawing a vertical boxenplot grouped by a categorical variable

plt.figure(figsize=(10,9))

sns.boxenplot(x=auto["body-style"] , y = auto["engine-size"] ,palette="Set1")

plt.show()

plt.figure(figsize=(11,9))

sns.boxenplot(x=auto["body-style"] , y = auto["engine-size"],palette="Set1")

plt.show()

sns.set(rc={"axes.facecolor":"#a1c45a" , "axes.grid" : False})

plt.figure(figsize=(11,9))

plt.gcf().text(.51, .84, "Box Plot", fontsize = 40, color='Black' ,ha='center', va='center')

sns.boxenplot(x=auto["body-style"] , y = auto["engine-size"],palette="Set1")

plt.show()

# Horizontal Boxen plot

sns.set_style("darkgrid")

plt.figure(figsize=(10,9))

sns.boxenplot(x = auto["engine-size"] ,y= auto["body-style"] ,palette="Set1")

plt.show()

# Show groups with different colors using "hue" (Nested grouping by two categorical variabl

plt.figure(figsize=(11,9))

sns.boxenplot(x=auto["body-style"] , y = auto["engine-size"], hue=auto["fuel-type"], palette={"diesel":'#FFB74D' , "gas":'#9CCC65'})

plt.show()

# Facet along the columns to show a categorical variable using "col" parameter

plt.figure(figsize=(11,9))

sns.catplot(x="body-style" , y = "engine-size", col="fuel-type", kind="boxen",palette="Set2" , height=7,data=auto)

plt.show()

6. Point plots

An alternative style for visualizing the same information is offered by the 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, 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:

plt.figure(figsize=(8,8))

sns.pointplot(auto['fuel-system'], auto['engine-size'])

plt.show()

plt.figure(figsize=(8,8))

sns.pointplot(auto['fuel-system'], auto['engine-size'], hue=auto['num-of-doors'])

plt.show()

#Separate the points for different hue levels along the categorical axis:



plt.figure(figsize=(8,8))

sns.pointplot(auto['fuel-system'], auto['engine-size'], hue=auto['num-of-doors'],dodge=True)

plt.show()

# use a different markers



plt.figure(figsize=(8,8))

sns.pointplot(auto['fuel-system'], auto['engine-size'], hue=auto['fuel-type'],dodge=True,markers=["o", "x"],linestyles=["-", "--"])

plt.show()

#Don’t draw a line connecting each point:

plt.figure(figsize=(8,8))

sns.pointplot(auto['fuel-system'], auto['engine-size'],join=False)

plt.show()

# Use a different color palette for the points:

plt.figure(figsize=(8,8))

sns.pointplot(auto['fuel-system'], auto['engine-size'], hue=auto['num-of-doors'], palette="Set2")

plt.show()

7.Strip Plot

Strip plot is a scatter plot where one of the variables is categorical.A strip plot is drawn on its own. It is a good complement to a boxplot or violinplot in cases where all observations are shown along with some representation of the underlying distribution. It is used to draw a scatter plot based on the category.

plt.figure(figsize=(11,8))

sns.stripplot(auto['city-mpg'])

plt.show()

plt.figure(figsize=(11,8))

sns.stripplot(auto['fuel-type'], auto['city-mpg'])

plt.show()

plt.figure(figsize=(16,8))

sns.stripplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"])

plt.show()

""" "Jitter" parameter signifies the amount of jitter to apply.

This can be extremely useful when we have large clusters of data points"""



plt.figure(figsize=(11,8))

sns.stripplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"],jitter=.3)

plt.show()

# Flip x and y inputs to make a horizontal strip plot

plt.figure(figsize=(11,8))

sns.stripplot(y=auto["body-style"] ,palette="Set1", x = auto["engine-size"] , jitter=True)

plt.show()

# Adjust the linewidth of the edges of the circles using "linewidth" parameter

# Adjust the size of the circles using the "size" parameter

plt.figure(figsize=(14,10))

sns.stripplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"],linewidth=2,size=8)

plt.show()

# Using set2 pallette

plt.figure(figsize=(14,10))

sns.stripplot(x=auto["body-style"] ,palette="Set2", y = auto["engine-size"],hue=auto["fuel-type"],linewidth=2,size=8)

plt.show()

# # Separate the strips for different hue levels along the categorical axis using "dodge=True"

plt.figure(figsize=(14,10))

sns.stripplot(x=auto["body-style"] ,palette="Set2", y = auto["engine-size"],hue=auto["fuel-type"],linewidth=2,size=8,dodge=True)

plt.show()

plt.figure(figsize=(16,10))

sns.stripplot(x=auto["body-style"] ,palette="Set2", y = auto["engine-size"],hue=auto["fuel-type"],marker = "o",size=30,alpha = .15)

plt.show()

# Drawing stripplot on top of a box plot



plt.figure(figsize=(11,8))

sns.stripplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"],hue=auto["fuel-type"],jitter=True, color="black",linewidth=2,size=8)

sns.boxplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"] , color='black')

plt.show()

plt.figure(figsize=(10,9))

sns.set(rc={"axes.facecolor":"#b0deff","axes.grid":False,

'xtick.labelsize':15,'ytick.labelsize':15,

'axes.labelsize':20,'figure.figsize':(20.0, 9.0)})

params = dict(data=auto ,x = auto["body-style"] ,y = auto["engine-size"] ,hue=auto["fuel-type"],dodge=True)

sns.stripplot(**params , size=9,jitter=0.35,palette=['#FF8F00','#558B2F'],edgecolor='black')

sns.boxplot(**params ,palette=['#909497','#D0D3D4'],linewidth=4)

plt.show()

# Drawing stripplot on top of a violin plot

plt.figure(figsize=(14,10))

sns.stripplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"],hue=auto["fuel-type"],jitter=True, color="black",linewidth=2,size=8)

sns.violinplot(x=auto["body-style"] ,palette="Set1", y = auto["engine-size"],hue=auto["fuel-type"],scale="count")

plt.show()

8.Facet Grid

Multi-plot grid for plotting. A FacetGrid can be drawn with up to three dimensions − row, col, and hue.

FacetGrid class helps in visualizing distribution of one variable as well as the relationship between multiple variables separately within subsets of your dataset using multiple panels.

A FacetGrid can be drawn with up to three dimensions ? row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.

FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid. The variables should be categorical and the data at each level of the variable will be used for a facet along that axis.

# Facet along the columns to show a categorical variables using "col" parameter (univariate

plt.figure(figsize=(8,8))

g = sns.FacetGrid(auto, col="fuel-type")

g = g.map(plt.hist, "wheel-base", edgecolor ='w', linewidth=2)

plt.show()

# Changing color of bars

g = sns.FacetGrid(auto, col="fuel-type" , row = "body-style" , height=3, aspect=1)

g = g.map(plt.hist, "engine-size" , color = '#F39C12',edgecolor ='w', linewidth=1)

# Bivariate function on each facet

g = sns.FacetGrid(auto, col="body-style" , row = "fuel-type" , height=3, aspect=1)

g = g.map(plt.scatter, "engine-size" , "wheel-base")

# Changing size of dots -> s = 80

g = sns.FacetGrid(auto, col="body-style" , row = "fuel-type" , height=3, aspect=1)

g = g.map(plt.scatter, "engine-size" , "wheel-base" , color = '#FF6600',edgecolor="w", s=80)

# Show groups with different colors using "hue"

g = sns.FacetGrid(auto, col="body-style" , row = "fuel-type" , hue="num-of-doors" ,height=3, aspect=1)

g = g.map(plt.scatter, "wheel-base" , "engine-size" , edgecolor="w", s=70)

# Showing legend -> g.add_legend()

g = sns.FacetGrid(auto, col="body-style" , row = "fuel-type" , hue="num-of-doors" ,height=3, aspect=1)

g = g.map(plt.scatter, "wheel-base" , "engine-size",edgecolor="w", s=70)

g.add_legend()

# Use different markers for each level of the hue variable

pal1 = dict(front="#ff7315", rear="#8cba51")

kws = dict(s=70, linewidth=1, edgecolor="w")

kws1 = dict(height=3, aspect=1,palette=pal1 , hue_kws=dict(marker=["^", "v"]))

g = sns.FacetGrid(auto, col="body-style" , row = "fuel-type" , hue="engine-location" , **kws1)

g = g.map(plt.scatter, "wheel-base" , "engine-size",**kws)

g.add_legend()

plt.show()

g = sns.FacetGrid(auto, col="body-style" , row = "fuel-type" ,height=3, aspect=1)

g = g.map(plt.bar, "wheel-base" , "engine-size",edgecolor="w" , color = '#8cba51')

g.add_legend()

9.Joint Grid

Grid for drawing a bivariate plot with marginal univariate plots.Many plots can be drawn by using the figure-level interface jointplot() .

#Add plots using default parameters

g = sns.JointGrid(x="wheel-base", y="engine-size", data=auto, height = 10)

g = g.plot(sns.regplot, sns.distplot)

# Changing color of plots

g = sns.JointGrid(x="wheel-base", y="engine-size", data=auto, height = 10)

g = g.plot_joint(sns.scatterplot, color="#FF6600",s=50)

g = g.plot_marginals(sns.distplot, color="#FF6600")

# Remove kernel density estimate from the marginal plots

g = sns.JointGrid(x="wheel-base", y="engine-size", data=auto, height = 10)

g = g.plot_joint(sns.scatterplot, color="#FF6600")

g = g.plot_marginals(sns.distplot,kde= False, color="#FF6600")

# kde plot in the margins and the interior into a shaded countour plot

g = sns.JointGrid(x="wheel-base", y="engine-size", data=auto, height = 8)

g = g.plot_joint(sns.kdeplot)

g = g.plot_marginals(sns.kdeplot, shade=True)

# Set Axis limits

g = sns.JointGrid(x="wheel-base", y="engine-size", data=auto, height = 10 , xlim=(80,100) , ylim=(20,300))

g = g.plot_joint(sns.kdeplot , cmap="OrRd_r")

g = g.plot_marginals(sns.kdeplot, shade=True , color = 'orange')

# Changing background of marginal graphs

g = sns.JointGrid(x="wheel-base", y="engine-size", data=auto, height = 10)

g = g.plot_joint(sns.scatterplot, color="#FF6600",s=50)

g= g.plot_marginals(sns.distplot,kde=False , color = 'Blue')

g.ax_marg_x.set_facecolor('#f8fab8')

g.ax_marg_y.set_facecolor('#f8fab8')

10.Pair Grid

Pair Grid is a Subplot grid for plotting pairwise relationships in a dataset. Different axes-level plotting functions can be used to draw bivariate plots in the upper and lower triangles, and the the marginal distribution of each variable can be shown on the diagonal.

#scatterplot for each pairwise relationship

g = sns.PairGrid(auto)

g = g.map(plt.scatter)

plt.show()

# Histogram on the diagonal

g = sns.PairGrid(auto)

g = g.map_offdiag(plt.scatter)

g = g.map_diag(plt.hist)

plt.show()

# Show groups with different colors using "hue"

g = sns.PairGrid(auto , hue='fuel-type')

g = g.map_offdiag(plt.scatter)

g = g.map_diag(plt.hist)

g = g.add_legend()

plt.show()

g = sns.PairGrid(auto , hue='fuel-type', palette="husl")

g = g.map_offdiag(plt.scatter)

g = g.map_diag(plt.hist)

g = g.add_legend()

plt.show()

# Plot a subset of variables

g = sns.PairGrid(auto , hue='fuel-type' ,vars=["wheel-base" , "height" , "width"],height=5, aspect=1)

g = g.map_offdiag(plt.scatter , edgecolor="w", s=130)

g = g.map_diag(plt.hist , edgecolor ='w', linewidth=2)

g = g.add_legend()

plt.show()

g = sns.PairGrid(auto , hue='fuel-type' ,x_vars=["wheel-base" ,"height"],y_vars=["wheel-base" , "height"],height=6, aspect=1 , hue_kws={"marker": ["o", "^", "v"]})

g = g.map(plt.scatter , edgecolor="w", s=130)

g = g.add_legend()

plt.show()

# Using different plots on the upper and lower triangles

g = sns.PairGrid(auto ,vars=["length" , "height" , "width"],height=5, aspect=1)

g = g.map_upper(sns.scatterplot , edgecolor="w", s=130)

g = g.map_lower(sns.kdeplot)

g = g.map_diag(sns.kdeplot , lw= 2)

g = g.add_legend()

plt.show()

This article is adaptation of my work on kaggle :- https://www.kaggle.com/saurav9786/data-visualization-using-seaborn

Hope you liked the article .

Thanks,

Saurav Anand

Gain Access to Expert View — Subscribe to DDI Intel