Hello! Welcome to the final lesson in our module on Python tools for AI.
In our last session, you mastered grouping and aggregation with Pandas. You learned to use the "Split-Apply-Combine" strategy to calculate summary statistics, like finding the average salary for each department. While powerful, tables of numbers can be hard to interpret. A visual representation is often much more intuitive.
This lesson directly addresses the learning outcome: Visualize data distributions and relationships using Matplotlib and Seaborn. We will take the summaries you learned to create and turn them into insightful plots. This process, known as Exploratory Data Analysis (EDA), is a critical first step in any machine learning project. It helps you understand your data's patterns, quirks, and relationships before you start building models.
We'll be using two key Python libraries:
- Matplotlib: The foundational plotting library in Python. It's powerful and highly customizable but can be verbose for complex plots.
- Seaborn: A high-level library built on top of Matplotlib. It excels at creating beautiful and informative statistical graphics with much less code.
As a software engineer, you can think of Matplotlib as a low-level graphics API that gives you fine-grained control, while Seaborn is a higher-level, domain-specific framework designed for statistical data visualization.

We will use both, leveraging Seaborn for its simplicity and dropping down to Matplotlib for customization when needed.
1. From Aggregations to Bar Plots
Let's start by visualizing the result of a groupby operation from our previous lesson. A bar plot is perfect for comparing a summary statistic across different categories.
First, let's recreate our employee DataFrame and the aggregated data showing the average salary per department.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np # We'll need numpy later
# Set a nice default style for our plots
sns.set_theme(style="whitegrid")
# Data from the previous lesson
data = {
'employee_id': [101, 102, 103, 104, 105, 106],
'department': ['Sales', 'IT', 'IT', 'Marketing', 'Sales', 'IT'],
'salary': [70000, 85000, 92000, 65000, 72000, 110000],
'years_at_company': [3, 5, 6, 2, 4, 8]
}
df = pd.DataFrame(data)
# The aggregation you learned to do
avg_salary_by_dept = df.groupby('department')['salary'].mean().reset_index()
print(avg_salary_by_dept)
# department salary
# 0 IT 95666.666667
# 1 Marketing 65000.000000
# 2 Sales 71000.000000
Now, let's plot this using Seaborn's barplot. We specify which column goes on the x-axis (department) and which goes on the y-axis (salary).
plt.figure(figsize=(8, 5)) # Use Matplotlib to set the figure size
ax = sns.barplot(data=avg_salary_by_dept, x='department', y='salary')
ax.set_title('Average Salary by Department') # Matplotlib-style customization
plt.show()
This simple plot immediately tells a story: the IT department has a significantly higher average salary than the others.
The resource below provides a great overview of the most common plot types. We'll touch on several of these throughout the lesson.
Comprehensive Data Visualization with Matplotlib and Seaborn
The 'Comprehensive Data Visualization with Matplotlib and Seaborn' guide provides a great survey of different plot types. Let's look at the basic plots section to get an idea of the landscape.
Skim through Section 1, 'Basic Plots'. Pay attention to the purpose of each plot: Line Plot (trends over time), Scatter Plot (relationships), Bar Plot (categorical data), and Histogram (distributions). We've just created a Bar Plot.
2. Exploring Data Distributions
Understanding the distribution of a single variable is fundamental. How are values spread out? Are they clustered? Are there outliers? Histograms and Kernel Density Estimates (KDEs) are the primary tools for this.
For these examples, let's use a richer, built-in Seaborn dataset called penguins.
penguins = sns.load_dataset("penguins")
penguins.head()
# species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
# 0 Adelie Torgersen 39.1 18.7 181.0 3750.0 Male
# 1 Adelie Torgersen 39.5 17.4 186.0 3800.0 Female
# 2 Adelie Torgersen 40.3 18.0 195.0 3250.0 Female
# 3 Adelie Torgersen NaN NaN NaN NaN NaN
# 4 Adelie Torgersen 36.7 19.3 193.0 3450.0 Female
Histograms and KDE Plots
A histogram bins your data and shows the count of observations in each bin. A KDE plot is essentially a smoothed version of a histogram.
The official Seaborn tutorial provides the best explanation of these plots. It covers the key parameters you'll need to control their appearance and interpretation.
Visualizing distributions of data - Seaborn
The official Seaborn documentation is an excellent resource. Let's read its guide on visualizing distributions, which covers histograms and KDE plots in detail.
Read the sections 'Plotting univariate histograms' and 'Kernel density estimation'. Focus on understanding the trade-offs: histograms are intuitive but depend on bin size, while KDEs are smooth but can sometimes be misleading (e.g., showing negative values for a positive-only variable).
Let's see this in action. We'll plot the distribution of flipper lengths.
# Create a figure with two subplots side-by-side
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
# Histogram
sns.histplot(data=penguins, x='flipper_length_mm', ax=axes[0])
axes[0].set_title('Histogram of Flipper Length')
# KDE Plot
sns.kdeplot(data=penguins, x='flipper_length_mm', fill=True, ax=axes[1])
axes[1].set_title('KDE Plot of Flipper Length')
plt.show()
Both plots show a "bimodal" distribution (two peaks), suggesting there might be two distinct groups of penguins in our data. How can we investigate this?
Seaborn's hue parameter is perfect for this. It automatically splits the data by a categorical variable and colors the plot accordingly.
plt.figure(figsize=(10, 6))
sns.kdeplot(data=penguins, x='flipper_length_mm', hue='species', fill=True)
plt.title('Flipper Length Distribution by Species')
plt.show()
Now it's clear! The Gentoo penguins have much longer flippers than the Adelie and Chinstrap penguins, which explains the two peaks we saw earlier.
3. Visualizing Relationships Between Variables
Now let's move from single variables to the relationships between them.
Scatter Plots: Two Numeric Variables
The classic way to see the relationship between two continuous variables is a scatter plot. Let's see if there's a relationship between a penguin's bill length and bill depth.
plt.figure(figsize=(10, 6))
sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', hue='species')
plt.title('Bill Length vs. Bill Depth')
plt.show()
This plot reveals different patterns for each species. For example, Adelie penguins seem to have a negative correlation (as bill length increases, depth tends to decrease), while Gentoo penguins show a positive correlation.
Box Plots: Numeric vs. Categorical
What if you want to compare a numeric variable's distribution across several categories? This is exactly what a box plot is for. It's a fantastic way to visualize the output of a groupby operation.
Let's compare the body_mass_g across the three species.
plt.figure(figsize=(10, 6))
sns.boxplot(data=penguins, x='species', y='body_mass_g')
plt.title('Body Mass Distribution by Species')
plt.show()
The box plot concisely shows the median (the line in the box), the interquartile range (the box itself), and potential outliers (the dots). We can see that Gentoo penguins are, on average, much heavier than the other two species.
Test your understanding!
Using the df DataFrame of employees, create a box plot to visualize the distribution of salary for each department. What does it tell you?
Show answer
plt.figure(figsize=(8, 5))
sns.boxplot(data=df, x='department', y='salary')
plt.title('Salary Distribution by Department')
plt.show()
The plot shows that the 'IT' department not only has the highest average salary but also the widest range of salaries. The 'Sales' department has a very tight salary distribution, while 'Marketing' has only one data point, so its "box" is just a line.
4. The Big Picture: Matrix and Paired Plots
Sometimes you want a quick overview of all variables in your dataset. Seaborn has amazing functions for this.
Heatmaps: Visualizing Correlations
A correlation matrix measures the linear relationship between all pairs of numeric variables. A value of 1 means a perfect positive correlation, -1 a perfect negative correlation, and 0 means no linear correlation. A heatmap is the perfect way to visualize this matrix.
# Select only numeric columns and calculate the correlation matrix
numeric_penguins = penguins.select_dtypes(include=np.number)
correlation_matrix = numeric_penguins.corr()
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')
plt.title('Correlation Matrix of Penguin Measurements')
plt.show()
The annot=True argument displays the correlation values on the map. We can instantly see a strong positive correlation (0.87) between flipper length and body mass, which makes intuitive sense.
Pair Plots: The Ultimate EDA Tool
Finally, the pairplot function is a powerful tool that creates a matrix of plots showing every pairwise relationship in your dataset. It's a fantastic one-liner to get a holistic view of your data.
# This might take a few seconds to render
sns.pairplot(penguins, hue='species')
plt.show()
The pairplot gives you:
- Scatter plots for every pair of numeric variables on the off-diagonals.
- Histograms or KDE plots for each individual variable on the diagonal.
- The ability to see how these relationships and distributions differ when colored by a categorical variable like
species.
This single command generates a comprehensive report, making it an indispensable tool for initial data exploration.
Conclusion
In this lesson, you've learned how to bring data to life through visualization, a skill that's essential for any AI practitioner. You've moved from looking at tables of numbers to seeing the stories they contain.
Key Takeaways:
- Matplotlib is the foundational library for control, while Seaborn is the high-level tool for beautiful statistical plots.
- Bar plots are excellent for visualizing aggregated summaries (like the output of a
groupby). - Histograms and KDE plots help you understand the distribution of a single variable.
- Scatter plots show the relationship between two numeric variables, while Box plots compare a numeric variable across different categories.
- Heatmaps are ideal for visualizing correlation matrices.
- Pair plots provide a rapid, comprehensive overview of all distributions and pairwise relationships in your dataset.
Next up:
You have now completed the module on the foundational Python tools for AI! You can load, inspect, clean, group, and visualize data. With these Exploratory Data Analysis skills in hand, you are ready to start building models. In the next module, Fundamentals of Model Training, we will begin by exploring the core concepts of supervised learning and implement your first machine learning model from scratch.