Visualization With Seaborn
By: Yuke Liu
Tags: Data Science, Seaborn, Matplotlib, Data Visualization

Seaborn is a Python data visualization library based on Matplotlib.

It provides a high-level interface for drawing attractive and informative statistical graphics. It provides choices for plot style and color defaults, defines simple high-level functions for common statistical plot types, and integrates with the functionality provided by Pandas DataFrames.

The main idea of Seaborn is that it provides high-level commands to create a variety of plot types useful for statistical data exploration, and even some statistical model fitting.

1.0.1 Table of Contents

Creating basic plots Advance Categorical plots in Seaborn Density plots Pair plots

# importing required libraries

import seaborn as sns

sns.set()

sns.set(style='darkgrid') import numpy as np

import pandas as pd #importing matplotlib

import matplotlib.pyplot as plt

%matplotlib inline import warnings

warnings.filterwarnings("ignore")

plt.rcParams['figure.figsize']=(10,10)

In this notebook, we will use the Big Mart Sales Data. You can download the data from Github: https://github.com/Yuke217

# read the dataset

df = pd.read_csv("dataset/bigmart_data.csv")

# drop the null values

df = df.dropna(how="any")

# View the top results

df.head()

1.0.2 Creating basic plots

Let’s have a look at how can you create some basic plots in seaborn in a single line for which multiple lines were required in Matplotlib.

1.0.2.1 Line Chart

With some datasets, you may want to understand changes in one variable as a function of time or a similarly continuous variable.

In seaborn, this can be accomplished by the lineplot() function, either directly or with relplot by setting kind=”line”:

# line plot using lineplot()

sns.lineplot(x="Item_Weight", y="Item_MRP",data=df[:50])

1.0.2.2 Bar chart

In seaborn, you can create a bar chart by simply using the barplot function.

function. Notice that to achieve the same thing in Matplotlib, we had to write extra code just to group the data category wise.

And then we had to write much more code to make sure that the plot comes out correct.

sns.barplot(x="Item_Type", y="Item_MRP", data=df[:5])

1.0.2.3 Histogram

You can create a histogram in seaborn by using distplot().

sns.distplot(df['Item_MRP'])

1.0.2.4 Box plots

You can use Boxplot() for creating boxplots in seaborn

for creating boxplots in seaborn Let’s try to visualize the distribution of Item_Outlet_Sales of items.

sns.boxplot(df['Item_Outlet_Sales'], orient='vertical')

1.0.2.5 Violin plot

A violin plot plays a similar role as a box and whisker plot.

It shows the distribution of quantitative data across several levels of one(or more) categorical variables such that those distributions can be compared.

Unlike a box plot, in which all of the plot components correspond to actual data points, the violin plot features a kernel density estimation of the underlying distribution.

You can create a violin plot using the violinplot() in seaborn

sns.violinplot(df['Item_Outlet_Sales'], orient='vertical')

1.0.2.6 Scatter plot

It depicts the relationship between two variables using a cloud of points, where each point represents an observation in the dataset.

You can use relplot() with the option of kind=scatter to plot a scatter plot in seaborn.

with the option of kind=scatter to plot a scatter plot in seaborn. Notice the default option is scatter

# scatter plot

sns.relplot(x="Item_MRP", y="Item_Outlet_Sales", data = df[:200], kind="scatter")

1.0.2.7 Hue semantic

We can also add another dimension to the plot by coloring the points according to a third variable. In seaborn, this is referred to as using a “Hue semantic”.

sns.relplot(x="Item_MRP", y="Item_Outlet_Sales", hue="Item_Type", data=df[:200])

Remember the line chart that we created earlier, When we have hue semantic, we can create more complex line plots in seaborn.

semantic, we can create more complex line plots in seaborn. In the following example, different line plots for different categories of Outlet_Size are made.

# different line plots for different categories of the Outlet_Size

sns.lineplot(x="Item_Weight", y="Item_MRP", hue="Outlet_Size", data=df[:100])

1.0.2.8 Bubble plot

We utilize the hue semantic to color bubbles by their Item_Visibility and at the same time use it as size of individual bubbles.

# bubble plot

sns.relplot(x="Item_MRP", y="Item_Outlet_Sales", data=df[:200],kind="scatter", size="Item_Visibility", hue="Item_Visibility")

1.0.2.9 Category wise sub plot

You can also create plots based on category in seaborn.

in seaborn. We have created scatter plots for each Outlet_Size

Now we create three plots based on different Outlet_Size using col.

# subplots for each of the category of Outlet_Size

sns.relplot(x="Item_Weight", y="Item_Visibility", hue= 'Outlet_Size',col ="Outlet_Size",data=df[:100] )

1.1 2. Advance categorical plots in seaborn

For categorical variables we have three different families in seaborn.

Categorical scatterplots:

stripplot() (with kind=”strip”; the default)

swarmplot() (with kind=”swarm”)

Categorical distribution plots:

boxplot() (with kind=”box”)

violinplot() (with kind=”violin”)

Boxenplot() (with kind=”bowen”)

Categorical estimate plots:

pointplot() (with kind=”point”)

barplot() (with kind=”bar”)

The default representation of the data in catplot() uses a scatterplot.

1.1.1 a. Categorical scatterplots

1.1.1.1 Strip plot

Draws a scatterplot where one variable is categorical.

You can create this by passing kind=strip in the catplot .

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales", kind="strip", data=df[:250])

1.1.1.2 Swarm plot

This function is similar to stripplot() , but the points are adjusted so that they don't overlap.

, but the points are adjusted so that they don't overlap. This gives a better representation of the distribution of values, but it does not scale well to large numbers of observations. This style of plot is sometimes called a “beeswarm”.

You can created this by passing kind=swarm in the catplot .

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales", kind='swarm',data=df[:250])

1.1.2 b. Categorical distribution plots

1.1.2.1 Box Plots

Box plot shows the three quartile values of the distribution along with the extreme values.

The “whiskers” extend to points that lie within 1.5 IQRs of the lower and upper quartile, and then observations that fall ourside this range are displayed independently.

This means that each value in the boxplot corresponds to an actual observation in the data.

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales", kind="box", data=df)

1.1.2.2 Violin Plots

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales", kind="violin",data=df)

1.1.2.3 Boxen plots

This style of plot was originally named a “letter value” plot because it shows a large number of quantiles that are defined as “letter values”.

It is similarto a box plot in plotting a nonparametric 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.

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales", kind="boxen",data=df)

1.1.2.4 Point plot

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales",kind="point",data=df)

1.1.2.5 Bar plots

sns.catplot(x="Outlet_Size", y="Item_Outlet_Sales", kind="bar",data=df)

1.2 3. Density Plots

Rather than a histogram, we can get a smooth estimate of the distribution using a kernel density estimation, which Seaborn does with sns.dkeplot:

A Density Plot visualises the distribution of data over a continuous interval or time period.

Density plot allows for smoother distribution by smoothing out noise. The peaks of a Density Plot help display where values are concentrated over the interval.

An advantage Density Plots have over Histograms is that they’re better at determining the distribution shape because they’re not affected by the number of bins used (each bar used in a typical histogram).

# distribution of Item Visibility

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

sns.kdeplot(df["Item_Visibility"],shade=True)

# distribution of Item MRP

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

sns.kdeplot(df["Item_MRP"],shade=True)

1.2.1 Histogram and Density Plot

Histograms and KDE can be combined using distplot:

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

sns.distplot(df['Item_Outlet_Sales'])

1.3 4. Pair plots

When you generalize joint plots to datasets of larger dimentions, you end up with pair plots. This is very useful for exploring correlations between multidimensional data, when you’d like to plot all pairs of values against each other.

We’ll demo this with the well-known Iris dataset, which lists measurements of petals and sepals of three iris species:

iris = sns.load_dataset("iris")

iris.head()