Seaborn Overlays
In this lesson, you will learn how to combine Seaborn visualizations with Matplotlib. You will understand how to create statistical plots, add them to existing Matplotlib Axes, customize charts, and combine multiple visualization elements in one Figure.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand Seaborn and its relationship with Matplotlib.
- Understand the concept of Seaborn overlays.
- Install and import Seaborn.
- Create statistical charts using Seaborn.
- Combine Seaborn and Matplotlib in one Figure.
- Use the Matplotlib Axes object with Seaborn.
- Overlay scatter plots and regression lines.
- Add statistical distributions to existing charts.
- Customize chart titles, labels, legends, and grids.
- Create multiple Seaborn plots using Matplotlib subplots.
2. Introduction to Seaborn
Seaborn is a Python data visualization library built on top of Matplotlib. It provides a high-level interface for creating attractive and informative statistical graphics.
Matplotlib provides detailed control over figures, axes, labels, and chart elements. Seaborn provides convenient functions for statistical visualizations such as scatter plots, distribution plots, box plots, and regression plots.
Both libraries can be used together. We can create a Matplotlib Figure and Axes, then use Seaborn functions to draw statistical visualizations inside the same Axes.
Example: Student Performance Analysis
Suppose we have student study hours and examination marks. We can use Matplotlib to create the Figure and Seaborn to display the relationship between study hours and marks.
We can also add a regression line to understand the general relationship between the two variables.
3. What Is a Seaborn Overlay?
A Seaborn overlay means adding one or more Seaborn visualizations to an existing Matplotlib plotting area.
For example, we can create a scatter plot using Seaborn and add a Matplotlib title, axis labels, grid, or additional graphical elements to the same Axes.
4. Installing Seaborn
Before creating Seaborn visualizations, install Seaborn along with Pandas and Matplotlib.
Installation Command
pip install seaborn pandas matplotlib
Importing Required Libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
The alias sns is the commonly used
convention for importing Seaborn.
Checking Seaborn Version
import seaborn as sns
print("Seaborn Version:", sns.__version__)
Output
Seaborn Version: Installed Seaborn version
5. Creating a Basic Seaborn Plot
Seaborn provides functions such as
scatterplot(), lineplot(),
and histplot() to create different
statistical visualizations.
Example: Student Marks
import seaborn as sns
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6]
marks = [35, 42, 50, 60, 75, 85]
sns.scatterplot(
x=study_hours,
y=marks
)
plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.show()
Output
Chart Type: Scatter Plot
X-axis: Study Hours
Y-axis: Marks
Study Hours Marks
1 35
2 42
3 50
4 60
5 75
6 85
A scatter plot displays the relationship
between study hours and examination marks.
6. Using Seaborn with Matplotlib Axes
Seaborn plotting functions support the
ax parameter. This parameter allows
us to draw a Seaborn chart inside an existing
Matplotlib Axes object.
Example
import seaborn as sns
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6]
marks = [35, 42, 50, 60, 75, 85]
# Create Matplotlib Figure and Axes
fig, ax = plt.subplots(figsize=(8, 5))
# Draw Seaborn plot on the existing Axes
sns.scatterplot(
x=study_hours,
y=marks,
ax=ax
)
# Customize using Matplotlib
ax.set_title("Student Performance")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Marks")
plt.show()
Output
Figure: One Matplotlib Figure
Axes: One Matplotlib Axes
Seaborn: Scatter plot displayed inside the Axes
Title: Student Performance
X-axis: Study Hours
Y-axis: Marks
ax
parameter is important when combining Seaborn
with an existing Matplotlib layout.
7. Overlaying Scatter Plots and Regression Lines
We can combine a Seaborn scatter plot with a regression line to understand the relationship between two numerical variables.
The regplot() function displays
data points along with a fitted regression model.
Example
import seaborn as sns
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6, 7]
marks = [35, 42, 50, 60, 75, 85, 90]
fig, ax = plt.subplots(figsize=(8, 5))
sns.scatterplot(
x=study_hours,
y=marks,
color="blue",
s=80,
ax=ax
)
sns.regplot(
x=study_hours,
y=marks,
scatter=False,
color="red",
ax=ax
)
ax.set_title("Study Hours and Marks")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Marks")
ax.grid(True, alpha=0.3)
plt.show()
Output
Chart Type: Scatter Plot with Regression Line
Blue points: Actual student data
Red line: Fitted regression line
X-axis: Study Hours
Y-axis: Marks
The regression line shows the general
linear trend in the sample data.
8. Overlaying Histograms and KDE Curves
A histogram displays the frequency distribution of numerical data. A KDE curve provides a smooth estimate of the data distribution.
We can use Seaborn's histplot()
function with kde=True to display
both elements in one chart.
Example: Examination Marks Distribution
import seaborn as sns
import matplotlib.pyplot as plt
marks = [
35, 40, 45, 50, 55,
60, 65, 70, 75, 80,
85, 90, 95
]
fig, ax = plt.subplots(figsize=(8, 5))
sns.histplot(
marks,
bins=5,
kde=True,
color="skyblue",
ax=ax
)
ax.set_title("Student Marks Distribution")
ax.set_xlabel("Marks")
ax.set_ylabel("Frequency")
plt.show()
Output
Chart Type: Histogram with KDE Curve
Histogram: Displays frequency distribution.
KDE Curve: Displays a smooth density estimate.
X-axis: Marks
Y-axis: Frequency / Density scale
Both visual elements are displayed in one Axes.
9. Overlaying Box Plots with Other Elements
A box plot summarizes numerical data using quartiles, median, whiskers, and possible outlier points.
We can create a Seaborn box plot inside a Matplotlib Axes and customize it using Matplotlib methods.
Example: Department-wise Salary
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = {
"Department": [
"IT", "IT", "IT", "IT",
"HR", "HR", "HR", "HR",
"Sales", "Sales", "Sales", "Sales"
],
"Salary": [
30000, 35000, 40000, 45000,
25000, 28000, 32000, 35000,
28000, 32000, 38000, 42000
]
}
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize=(8, 5))
sns.boxplot(
data=df,
x="Department",
y="Salary",
ax=ax
)
ax.set_title("Department-wise Salary Distribution")
ax.set_xlabel("Department")
ax.set_ylabel("Salary (₹)")
plt.show()
Output
Chart Type: Box Plot
X-axis: Department
Y-axis: Salary (₹)
Categories:
IT
HR
Sales
Each department displays a box plot
summarizing its salary distribution.
10. Adding Matplotlib Elements to Seaborn Plots
After creating a Seaborn chart, we can use Matplotlib Axes methods to add titles, labels, grid lines, axis limits, and annotations.
Example
import seaborn as sns
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6]
marks = [35, 42, 50, 60, 75, 85]
fig, ax = plt.subplots(figsize=(8, 5))
sns.scatterplot(
x=study_hours,
y=marks,
color="purple",
s=80,
ax=ax
)
# Matplotlib customization
ax.set_title("Student Marks Analysis")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Marks")
ax.set_xlim(0, 7)
ax.set_ylim(0, 100)
ax.grid(True, linestyle="--", alpha=0.5)
ax.axhline(
y=60,
color="red",
linestyle="--",
label="Passing Marks"
)
ax.legend()
plt.tight_layout()
plt.show()
Output
Chart Title: Student Marks Analysis
Scatter Points: Student marks
Red Dashed Line: Passing Marks = 60
X-axis Range: 0 to 7
Y-axis Range: 0 to 100
Grid: Enabled
Legend: Enabled
11. Combining Multiple Seaborn Visualizations
Multiple Seaborn functions can be used on the same Matplotlib Axes. This helps combine related visual elements in one chart.
Example: Scatter Plot and Regression Line
import seaborn as sns
import matplotlib.pyplot as plt
data = {
"StudyHours": [1, 2, 3, 4, 5, 6, 7],
"Marks": [35, 42, 50, 60, 75, 85, 90]
}
fig, ax = plt.subplots(figsize=(8, 5))
sns.scatterplot(
data=data,
x="StudyHours",
y="Marks",
color="blue",
s=80,
ax=ax
)
sns.regplot(
data=data,
x="StudyHours",
y="Marks",
scatter=False,
color="red",
ax=ax
)
ax.set_title("Combined Statistical Visualization")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Marks")
ax.grid(True, alpha=0.3)
plt.show()
Output
One Matplotlib Figure
One Matplotlib Axes
Visualization Elements:
1. Seaborn scatter plot
2. Seaborn regression line
3. Matplotlib title
4. Matplotlib axis labels
5. Matplotlib grid
All elements are displayed together.
12. Using Seaborn with Multiple Matplotlib Subplots
Matplotlib allows us to create multiple Axes inside one Figure. Each Axes can contain a different Seaborn visualization.
Example: Three Statistical Charts
import seaborn as sns
import matplotlib.pyplot as plt
data = {
"StudyHours": [1, 2, 3, 4, 5, 6],
"Marks": [35, 42, 50, 60, 75, 85]
}
fig, axes = plt.subplots(
1,
3,
figsize=(15, 4)
)
# First Axes: Scatter Plot
sns.scatterplot(
data=data,
x="StudyHours",
y="Marks",
ax=axes[0]
)
axes[0].set_title("Scatter Plot")
# Second Axes: Regression Plot
sns.regplot(
data=data,
x="StudyHours",
y="Marks",
ax=axes[1]
)
axes[1].set_title("Regression Plot")
# Third Axes: Histogram
sns.histplot(
data=data,
x="Marks",
bins=5,
ax=axes[2]
)
axes[2].set_title("Marks Distribution")
plt.tight_layout()
plt.show()
Output
Figure: One Matplotlib Figure
Axes 1: Scatter Plot
Axes 2: Regression Plot
Axes 3: Histogram
Each Axes contains a separate Seaborn visualization.
All three charts are displayed in one Figure.
13. Applying Seaborn Themes
Seaborn provides built-in themes that control the overall appearance of statistical charts.
The set_theme() function can be used
to configure the visual style before creating
plots.
Available Styles
| Style | Description |
|---|---|
darkgrid |
Dark background with grid lines. |
whitegrid |
White background with grid lines. |
dark |
Dark background without the default grid. |
white |
White background without the default grid. |
ticks |
White background with axis ticks. |
Example
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid")
study_hours = [1, 2, 3, 4, 5, 6]
marks = [35, 42, 50, 60, 75, 85]
fig, ax = plt.subplots(figsize=(8, 5))
sns.scatterplot(
x=study_hours,
y=marks,
ax=ax
)
ax.set_title("Student Performance")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Marks")
plt.show()
Output
Seaborn Theme: whitegrid
Chart Type: Scatter Plot
Background: White
Grid: Visible
The selected Seaborn theme is applied
to the visualization.
14. Using Seaborn Color Palettes
Seaborn provides colour palettes that help create consistent and attractive visualizations.
We can use the palette parameter
to control the colours used for categorical data.
Example: Department-wise Performance
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = {
"Department": [
"IT", "IT", "HR", "HR",
"Sales", "Sales"
],
"Marks": [85, 90, 75, 80, 70, 88]
}
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize=(8, 5))
sns.barplot(
data=df,
x="Department",
y="Marks",
hue="Department",
palette="Set2",
legend=False,
ax=ax
)
ax.set_title("Department-wise Performance")
ax.set_xlabel("Department")
ax.set_ylabel("Marks")
plt.show()
Output
Chart Type: Bar Chart
Categories:
IT
HR
Sales
Palette: Set2
Each department is displayed using
a different colour from the selected palette.
15. Combining Pandas, Seaborn, and Matplotlib
Pandas, Seaborn, and Matplotlib can be used together in one data visualization workflow.
Pandas manages and prepares the dataset. Seaborn creates statistical visualizations, while Matplotlib provides control over the Figure and Axes.
Example: Complete Data Visualization Workflow
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Create DataFrame
data = {
"Month": ["Jan", "Feb", "Mar", "Apr", "May"],
"Sales": [20000, 25000, 30000, 35000, 40000],
"Profit": [4000, 5000, 6000, 7000, 9000]
}
df = pd.DataFrame(data)
# Create Figure and Axes
fig, ax = plt.subplots(figsize=(9, 5))
# Create Seaborn visualization
sns.lineplot(
data=df,
x="Month",
y="Sales",
marker="o",
label="Sales",
ax=ax
)
sns.lineplot(
data=df,
x="Month",
y="Profit",
marker="s",
label="Profit",
ax=ax
)
# Customize using Matplotlib
ax.set_title("Monthly Sales and Profit")
ax.set_xlabel("Month")
ax.set_ylabel("Amount (₹)")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
Output
Chart Title: Monthly Sales and Profit
Data Source: Pandas DataFrame
Seaborn Visualizations:
1. Sales line
2. Profit line
Matplotlib Customization:
1. Figure size
2. Chart title
3. Axis labels
4. Grid
5. Legend
Both data series are displayed in one Axes.
16. Common Mistakes When Using Seaborn Overlays
1. Forgetting the Axes Parameter
If you want to draw a Seaborn chart inside
an existing Matplotlib Axes, pass that Axes
object using the ax parameter.
2. Mixing Different Data Columns
Make sure the selected X and Y variables contain suitable data for the chart type.
3. Repeating Chart Labels
When multiple plots are combined, use clear labels and legends to identify each data series.
4. Using Incorrect Plot Types
Select the appropriate statistical chart according to the data being analysed.
5. Forgetting Layout Adjustment
Use plt.tight_layout() when
needed to reduce overlap between titles,
labels, and subplot areas.
17. Best Practices for Seaborn Overlays
Recommended Practices
- Use Matplotlib Figure and Axes for layout control.
- Pass the correct Axes using the
axparameter. - Use Seaborn for statistical visualizations.
- Use Matplotlib methods for additional customization.
- Choose meaningful colours and palettes.
- Use legends when displaying multiple data series.
- Keep titles and axis labels clear.
- Avoid adding too many visual elements to one chart.
- Use
plt.tight_layout()when necessary.
18. Classroom Practical Activity
Activity: Student Performance Visualization
Create a DataFrame containing student study hours, marks, and department details.
| Student | Department | Study Hours | Marks |
|---|---|---|---|
| Rahul | IT | 2 | 45 |
| Priya | IT | 5 | 85 |
| Amit | HR | 3 | 60 |
| Sneha | HR | 6 | 90 |
Complete the following tasks:
- Create a Matplotlib Figure and Axes.
- Create a Seaborn scatter plot for study hours and marks.
- Add a regression line to the scatter plot.
- Use department as a categorical variable.
- Customize the chart title and axis labels.
- Apply a Seaborn theme.
- Display the final chart using Matplotlib.
19. Practice Questions
Beginner Level
- What is Seaborn?
- How is Seaborn related to Matplotlib?
- Which command installs Seaborn?
- What is the commonly used Seaborn import alias?
- What is a Seaborn overlay?
Intermediate Level
- How do you create a Seaborn scatter plot?
- What is the purpose of the
axparameter? - How do you add a regression line to a scatter plot?
- How can you combine a histogram and KDE curve?
- How do you apply a Seaborn theme?
Practical Level
- Create a scatter plot using Seaborn and Matplotlib.
- Display a regression line on an existing Axes.
- Create a histogram with a KDE curve.
- Display three Seaborn plots using Matplotlib subplots.
- Combine Pandas, Seaborn, and Matplotlib in one program.
Summary
In this lesson, you learned about Seaborn and its integration with Matplotlib. Seaborn is built on top of Matplotlib and provides a high-level interface for creating statistical visualizations.
You explored how to create Seaborn scatter plots, regression plots, histograms, KDE curves, and box plots. You also learned how to use the Matplotlib Axes object to place Seaborn visualizations inside an existing Figure.
You also practised combining Pandas, Seaborn, and Matplotlib in one workflow. Pandas manages the data, Seaborn creates statistical plots, and Matplotlib provides detailed control over the visualization.
Understanding Seaborn overlays helps developers create meaningful statistical visualizations while maintaining the flexibility of Matplotlib.