Introduction
In the previous article, we studied about MatPlotLib, its functions and their python implementations. In this article, we will be studying each of the seaborn functions and their python implementation.
What is Python Seaborn?
Seaborn is a library for making statistical graphics in Python. It is built on top of matplotlib and closely integrated with pandas data structures.
Here is some of the functionality that seaborn offers:
- A dataset-oriented API for examining relationships between multiple variables
- Specialized support for using categorical variables to show observations or aggregate statistics
- Options for visualizing univariate or bivariate distributions and for comparing them between subsets of data
- Automatic estimation and plotting of linear regression models for different kinds of dependent variables
- Convenient views onto the overall structure of complex datasets
- High-level abstractions for structuring multi-plot grids that let you easily build complex visualizations
- Concise control over matplotlib figure styling with several built-in themes
- Tools for choosing colour palettes that faithfully reveal patterns in your data
Seaborn aims to make visualization a central part of exploring and understanding data. Its dataset-oriented plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots
The official website is seaborn.pydata.org
Installing Seaborn
1. Ubuntu/Linux
- sudo apt update -y
- sudo apt upgrade -y
- sudo apt install python3-tk python3-pip -y
- sudo pip install seaborn -y
- conda install -c anaconda seaborn
Difference Between Matplotlib and Seaborn
| MatPlotLib | Seaborn | |
| Functionality | Matplotlib is mainly deployed for basic plotting. Visualization using Matplotlib generally consists of bars, pies, lines, scatter plots and so on. | Seaborn, on the other hand, provides a variety of visualization patterns. It uses fewer syntax and has easily interesting default themes. It specializes in statistics visualization and is used if one has to summarize data in visualizations and also show the distribution in the data. |
| Handling Multiple Figures | Matplotlib has multiple figures can be opened, but need to be closed explicitly. plt.close() only closes the current figure. plt.close(‘all’) would close em all. | Seaborn automates the creation of multiple figures. This sometimes leads to OOM (out of memory) issues. |
| Visualization | Matplotlib is a graphics package for data visualization in Python. It is well integrated with NumPy and Pandas. The pyplot module mirrors the MATLAB plotting commands closely. Hence, MATLAB users can easily transit to plotting with Python. | Seaborn is more integrated for working with Pandas data frames. It extends the Matplotlib library for creating beautiful graphics with Python using a more straightforward set of methods. |
| Data Frames and Arrays | Matplotlib works with data frames and arrays. It has different stateful APIs for plotting. The figures and aces are represented by the object and therefore plot() like calls without parameters suffices, without having to manage parameters. | Seaborn works with the dataset as a whole and is much more intuitive than Matplotlib. For Seaborn, replot() is the entry API with ‘kind’ parameter to specify the type of plot which could be line, bar, or any of the other types. Seaborn is not stateful. Hence, plot() would require passing the object. |
| Flexibility | Matplotlib is highly customizable and powerful. | Seaborn avoids a ton of boilerplate by providing default themes which are commonly used. |
| Use Cases |
Pandas uses Matplotlib. It is a neat wrapper around Matplotlib.
|
Seaborn is for more specific use cases. Also, it is Matplotlib under the hood. It is specially meant for statistical plotting. |
Seaborn Functions
1. seaborn.relplot()
Syntax
seaborn.relplot(x=None, y=None, hue=None, size=None, style=None, data=None, row=None, col=None, col_wrap=None, row_order=None, col_order=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, markers=None, dashes=None, style_order=None, legend='brief', kind='scatter', height=5, aspect=1, facet_kws=None, **kwargs)
It is a function that is a figure-level interface for drawing relational plots onto a FacetGrid.
- import seaborn as sns
- sns.set(style="white")
- # Load the example mpg dataset
- mpg = sns.load_dataset("mpg")
- # Plot miles per gallon against horsepower with other semantics
- sns.relplot(x="horsepower", y="mpg", hue="origin", size="weight",
- sizes=(400, 40), alpha=.5, palette="muted",
- height=6, data=mpg)

2. seaborn.scatterplot()
Syntax
seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, markers=True, style_order=None, x_bins=None, y_bins=None, units=None, estimator=None, ci=95, n_boot=1000, alpha='auto', x_jitter=None, y_jitter=None, legend='brief', ax=None, **kwargs)
Draws a scatter plot with the possibility of several semantic groupings.
- import seaborn as sns
- sns.set()
- # Load the example iris dataset
- planets = sns.load_dataset("planets")
- cmap = sns.cubehelix_palette(rot=-.5, as_cmap=True)
- ax = sns.scatterplot(x="distance", y="orbital_period",
- hue="year", size="mass",
- palette=cmap, sizes=(100, 100),
- data=planets)

3. seaborn.lineplot()
Syntax
seaborn.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator='mean', ci=95, n_boot=1000, sort=True, err_style='band', err_kws=None, legend='brief', ax=None, **kwargs)
Draws a line plot with the possibility of several semantic groupings.
- import numpy as np
- import pandas as pd
- import seaborn as sns
- sns.set(style="whitegrid")
- rs = np.random.RandomState(365)
- values = rs.randn(365, 4).cumsum(axis=0)
- dates = pd.date_range("1 1 2016", periods=365, freq="D")
- data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"])
- data = data.rolling(10).mean()
- sns.lineplot(data=data, palette="tab10", linewidth=2.5)

4. seaborn.catplot()
Syntax
seaborn.catplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=<function mean>, ci=95, n_boot=1000, units=None, order=None, hue_order=None, row_order=None, col_order=None, kind='strip', height=5, aspect=1, orient=None, color=None, palette=None, legend=True, legend_out=True, sharex=True, sharey=True, margin_titles=False, facet_kws=None, **kwargs)
Figure-level interface for drawing categorical plots onto a FacetGrid.
- import seaborn as sns
- sns.set(style="whitegrid")
- # Load the example exercise dataset
- df = sns.load_dataset("exercise")
- # Draw a pointplot to show pulse as a function of three categorical factors
- g = sns.catplot(x="pulse", y="time", hue="diet", col="kind",
- capsize=.6, palette="YlGnBu_d", height=6, aspect=.75,
- kind="point", data=df)
- g.despine(left=True)

5. seaborn.stripplot()
Syntax
seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=True, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
Draws a scatterplot where one variable is categorical.
- import pandas as pd
- import seaborn as sns
- import matplotlib.pyplot as plt
- sns.set(style="whitegrid")
- iris = sns.load_dataset("iris")
- # "Melt" the dataset to "long-form" or "tidy" representation
- iris = pd.melt(iris, "species", var_name="measurement")
- # Initialize the figure
- f, ax = plt.subplots()
- sns.despine(bottom=True, left=True)
- # Show each observation with a scatterplot
- sns.stripplot(x="measurement", y="value", hue="species",
- data=iris, dodge=True, jitter=True,
- alpha=.25, zorder=1)
- # Show the conditional means
- sns.pointplot(x="measurement", y="value", hue="species",
- data=iris, dodge=.532, join=False, palette="dark",
- markers="d", scale=.75, ci=None)
- # Improve the legend
- handles, labels = ax.get_legend_handles_labels()
- ax.legend(handles[3:], labels[3:], title="species",
- handletextpad=0, columnspacing=1,
- loc="lower right", ncol=3, frameon=True)

6. seaborn.swarmplot()
Syntax
seaborn.swarmplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
Draws a categorical scatterplot with non-overlapping points.
- import pandas as pd
- import seaborn as sns
- sns.set(style="whitegrid", palette="muted")
- # Load the example iris dataset
- iris = sns.load_dataset("iris")
- # "Melt" the dataset to "long-form" or "tidy" representation
- iris = pd.melt(iris, "species", var_name="measurement")
- # Draw a categorical scatterplot to show each observation
- sns.swarmplot(x="value", y="measurement", hue="species",
- palette=["r", "c", "y"], data=iris)

7. seaborn.boxplot()
Syntax
seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, notch=False, ax=None, **kwargs)
Draws a box plot to show distributions with respect to categories.
- import seaborn as sns
- import matplotlib.pyplot as plt
- sns.set(style="ticks")
- # Initialize the figure with a logarithmic x axis
- f, ax = plt.subplots(figsize=(7, 6))
- ax.set_xscale("log")
- # Load the example planets dataset
- planets = sns.load_dataset("planets")
- # Plot the orbital period with horizontal boxes
- sns.boxplot(x="distance", y="method", data=planets,
- whis="range", palette="vlag")
- # Add in points to show each observation
- sns.swarmplot(x="distance", y="method", data=planets,
- size=2, color=".6", linewidth=0)
- # Tweak the visual presentation
- ax.xaxis.grid(True)
- ax.set(ylabel="")
- sns.despine(trim=True, left=True)















Sarathlal SaseendranPosted Sep 26, 2019, 4:46 PM
Simply awesome article Rohit. Keep going. Thanks for sharing such a wonderful material.
Elavarasan RPosted Sep 26, 2019, 12:54 AM
Great. A very useful article. thankyou for sharing.