Tutorial 5: Data Visualization with Seaborn

Introduction

Seaborn is a Python library built on top of Matplotlib. It makes statistical visualization easier and produces attractive, informative charts with far less code.

Matplotlib → Basic plotting control
Seaborn → Statistical visualization → Patterns • Relationships • Distributions

You’ll learn to create: count plots, bar plots, histograms and density plots, box plots, scatter plots, heatmaps, and pair plots.


1. Install and Import Seaborn

If not already installed:

pip install seaborn

In a Jupyter Notebook:

%pip install seaborn

Import the libraries:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

(Seaborn is conventionally imported as sns — a nod to the character Samuel Norman Seaborn from The West Wing, which is where the library’s creator got the name.)


2. Create a Sample Dataset

data = {
    "Name": ["Amit", "Priya", "Rahul", "Sneha", "Vikram", "Anjali"],
    "Department": ["IT", "HR", "Finance", "IT", "Sales", "Finance"],
    "Salary": [75000, 60000, 85000, 90000, 65000, 95000],
    "Experience": [5, 3, 7, 8, 4, 10]
}

df = pd.DataFrame(data)
df

3. Count Plot

A count plot shows how many records fall into each category.

sns.countplot(data=df, x="Department")
plt.title("Employees by Department")
plt.xlabel("Department")
plt.ylabel("Number of Employees")
plt.show()

Use it for: department → number of employees, city → number of customers, category → number of products.


4. Bar Plot

A bar plot compares a numerical value across categories — for example, average salary by department.

sns.barplot(data=df, x="Department", y="Salary")
plt.title("Average Salary by Department")
plt.show()

Seaborn automatically calculates an aggregate (by default, the mean) for each category. You can also specify it explicitly:

sns.barplot(data=df, x="Department", y="Salary", estimator="mean")

5. Histogram

sns.histplot(data=df, x="Salary")
plt.title("Salary Distribution")
plt.show()

You can add a smooth density curve on top:

sns.histplot(data=df, x="Salary", kde=True)
plt.title("Salary Distribution")
plt.show()

What is kde=True? KDE stands for Kernel Density Estimate — it draws a smoothed curve approximating the shape of the underlying distribution, which is often easier to interpret at a glance than raw histogram bars.


6. Box Plot

A box plot summarizes a numerical column using five key statistics: minimum, maximum, median, and the two quartiles (25th and 75th percentiles) — and it also visually flags outliers.

sns.boxplot(data=df, y="Salary")
plt.title("Salary Distribution")
plt.show()

Compare salary by department:

sns.boxplot(data=df, x="Department", y="Salary")
plt.title("Salary by Department")
plt.show()

7. Scatter Plot

sns.scatterplot(data=df, x="Experience", y="Salary")
plt.title("Experience vs Salary")
plt.show()

This helps investigate: does salary tend to increase as experience increases? You can add a trend line using regplot():

sns.regplot(data=df, x="Experience", y="Salary")
plt.title("Experience vs Salary")
plt.show()

8. hue: Adding a Third Dimension

The hue parameter colors data points by an additional categorical variable:

sns.scatterplot(data=df, x="Experience", y="Salary", hue="Department")
plt.title("Experience vs Salary by Department")
plt.show()

Conceptually: X-axis → Experience, Y-axis → Salary, Hue (color) → Department. This lets you analyze multiple dimensions in a single chart.


9. Heatmap

A heatmap represents values using color intensity — most commonly used to visualize correlations.

First calculate correlations:

correlation = df[["Salary", "Experience"]].corr()
correlation

Then visualize:

sns.heatmap(correlation, annot=True)
plt.title("Correlation Heatmap")
plt.show()

annot=True displays the actual numeric correlation value inside each cell. Correlation values range from -1 (strong negative relationship) through 0 (no linear relationship) to +1 (strong positive relationship).


10. Pair Plot

A pair plot automatically creates a grid of scatter plots (and histograms) for every pair of numerical columns:

sns.pairplot(df[["Salary", "Experience"]])
plt.show()

It’s an efficient way to quickly scan for relationships across many variables at once, without writing a separate scatter plot for each pair.


11. Seaborn Styling

Seaborn ships with built-in visual themes:

sns.set_theme(style="whitegrid")

Other common styles:

sns.set_theme(style="darkgrid")
sns.set_theme(style="white")
sns.set_theme(style="ticks")

Then create your chart as usual:

sns.barplot(data=df, x="Department", y="Salary")
plt.title("Average Salary by Department")
plt.show()

12. Matplotlib vs. Seaborn

FeatureMatplotlibSeaborn
Main purposeGeneral visualizationStatistical visualization
ControlVery highHigh
Code requiredOften moreOften less
Default appearanceBasicMore polished
Statistical chartsManualBuilt-in
Works with PandasYesYes

Simple rule of thumb: Matplotlib gives you control. Seaborn gives you convenience and built-in statistical visualizations. In practice, they’re almost always used together:

import seaborn as sns
import matplotlib.pyplot as plt

sns.barplot(data=df, x="Department", y="Salary")
plt.title("Average Salary by Department")
plt.show()

Example: Visualizing Department Data

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = {
    "Department": ["IT", "IT", "IT", "HR", "HR", "Finance", "Finance", "Finance", "Sales"],
    "Salary": [75000, 90000, 85000, 60000, 65000, 85000, 95000, 88000, 65000]
}

df = pd.DataFrame(data)

sns.barplot(data=df, x="Department", y="Salary")
plt.title("Average Salary by Department")
plt.xlabel("Department")
plt.ylabel("Average Salary")
plt.show()

Possible insight: Finance has the highest average salary among the departments in this dataset.


Choosing the Right Seaborn Chart

  • Need to count categories? → countplot
  • Compare numerical values? → barplot
  • Understand distribution? → histplot
  • Find outliers? → boxplot
  • Study relationships? → scatterplot
  • Study correlations? → heatmap
  • Explore many variables at once? → pairplot

Scroll to Top