ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

All Courses

Data Visualization with Matplotlib and Seaborn
Chapter 1: Introduction to Data Visualization
What is Data Visualization?
Why Visualize Data in AI and Engineering?
Introduction to Matplotlib
Introduction to Seaborn
Relationship between Matplotlib and Seaborn
Setting Up Your Python Environment
Importing Libraries
Your First Simple Plot
Quiz for Chapter 1
Chapter 2: Fundamentals of Matplotlib Plotting
Anatomy of a Matplotlib Plot: Figure and Axes
Creating a Basic Plotting Script
Line Plots: Plotting Trends
Scatter Plots: Showing Relationships
Adding Titles and Labels
Changing Colors and Line Styles
Setting Axis Limits
Practice: Creating Simple Line and Scatter Plots
Quiz for Chapter 2
Chapter 3: Basic Matplotlib Plot Types
Bar Charts for Comparisons
Creating Vertical and Horizontal Bar Charts
Histograms for Distributions
Understanding Bins in Histograms
Pie Charts for Proportions
Stacking Plots
Hands-on Practical: Plotting Different Data Types
Quiz for Chapter 3
Chapter 4: Introduction to Seaborn for Enhanced Visuals
Seaborn's Role: High-Level Interface
Setting Seaborn Styles and Contexts
Seaborn Color Palettes
Creating Scatter Plots with Seaborn (scatterplot)
Creating Line Plots with Seaborn (lineplot)
Understanding Seaborn's Data Input Requirements
Practice: Recreating Plots with Seaborn
Quiz for Chapter 4
Chapter 5: Visualizing Data Distributions with Seaborn
Histograms and Kernel Density Estimates (histplot, kdeplot)
Visualizing Joint Distributions (jointplot)
Box Plots for Summary Statistics (boxplot)
Violin Plots: Combining Box Plots and KDE (violinplot)
Understanding Distribution Plot Choices
Hands-on Practical: Plotting Distributions
Quiz for Chapter 5
Chapter 6: Plotting Categorical Data using Seaborn
Understanding Categorical Data
Bar Plots for Aggregate Statistics (barplot)
Count Plots for Frequencies (countplot)
Box Plots for Categorical Variables (boxplot)
Strip Plots and Swarm Plots for Individual Points (stripplot, swarmplot)
Point Plots for Trends (pointplot)
Hands-on Practical: Visualizing Categorical Features
Quiz for Chapter 6
Chapter 7: Customizing and Saving Visualizations
Adding Text and Annotations to Plots
Managing Legends
Adjusting Figure Size and Layout
Using Matplotlib Object-Oriented API for Finer Control
Applying Seaborn Themes
Saving Plots to Files (PNG, JPG, PDF, SVG)
Choosing the Right File Format
Practice: Polishing Your Plots
Quiz for Chapter 7
Chapter 8: Plotting with Pandas DataFrames
Brief Introduction to Pandas Series and DataFrames
Loading Data into a DataFrame
Basic Plotting Directly from DataFrames
Using Matplotlib with DataFrame Columns
Using Seaborn with DataFrames
Filtering and Preparing Data for Plotting
Hands-on Practical: Visualizing Data from a File
Quiz for Chapter 8

Hands-on Practical: Plotting Distributions

Several Seaborn functions are used to visualize data distributions. These include histplot, kdeplot, boxplot, violinplot, and jointplot, which are applied to a real dataset to analyze distribution patterns.

Setting Up

First, ensure you have the necessary libraries imported. We'll use Seaborn for plotting, Matplotlib for potential adjustments (like controlling figure size), and Pandas to handle our data. We will use the built-in 'tips' dataset available directly within Seaborn. This dataset contains information about tips given in a restaurant.

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

# Load the example dataset
tips = sns.load_dataset("tips")

# Display the first few rows to understand the data
print(tips.head())

The output will show columns like total_bill, tip, sex, smoker, day, time, and size. These columns provide a mix of numerical and categorical data, perfect for exploring distributions.

Visualizing Single Variable Distributions: Histograms and KDE

Let's start by examining the distribution of the total_bill amount. A histogram is a great way to see the frequency of different bill ranges.

Histogram (histplot)

We can create a histogram of the total_bill column using sns.histplot().

plt.figure(figsize=(8, 5)) # Control figure size for better readability
sns.histplot(data=tips, x="total_bill")
plt.title("Distribution of Total Bill Amounts")
plt.xlabel("Total Bill ($)")
plt.ylabel("Frequency")
plt.show()

Distribution of total bill amounts. Most bills are between 10and10 and 10and20.

Histogram with Kernel Density Estimate (KDE)

Sometimes, a smooth curve representing the estimated probability density is helpful. We can add this using kde=True or create it separately with sns.kdeplot().

plt.figure(figsize=(8, 5))
sns.histplot(data=tips, x="total_bill", kde=True, color="#1098ad") # Using kde=True
plt.title("Distribution of Total Bill Amounts with KDE")
plt.xlabel("Total Bill ($)")
plt.ylabel("Frequency / Density")
plt.show()

# Or using kdeplot separately
plt.figure(figsize=(8, 5))
sns.kdeplot(data=tips, x="total_bill", color="#f76707", fill=True) # fill adds color under the curve
plt.title("KDE of Total Bill Amounts")
plt.xlabel("Total Bill ($)")
plt.ylabel("Density")
plt.show()

Smoothed Kernel Density Estimate (KDE) of total bill amounts, highlighting the peak around 15−15-15−20 and the right skew.

The KDE provides a smoother representation of the distribution's shape compared to the histogram's discrete bins.

Comparing Distributions: Box Plots and Violin Plots

Often, we want to compare the distribution of a numerical variable across different categories. Let's compare the total_bill distribution based on the day of the week.

Box Plot (boxplot)

A box plot summarizes the distribution using quartiles. The box represents the interquartile range (IQR), the line inside is the median, and the whiskers typically extend to 1.5 times the IQR. Points outside the whiskers are potential outliers.

plt.figure(figsize=(8, 6))
sns.boxplot(data=tips, x="day", y="total_bill", palette="viridis") # using a different palette
plt.title("Total Bill Distribution by Day")
plt.xlabel("Day of the Week")
plt.ylabel("Total Bill ($)")
plt.show()

Comparison of total bill distribution by day. Weekend days (Sat, Sun) tend to have higher median bills and a wider range compared to weekdays.

Violin Plot (violinplot)

A violin plot combines a box plot with a KDE plot, showing the distribution's shape alongside the summary statistics.

plt.figure(figsize=(8, 6))
sns.violinplot(data=tips, x="day", y="total_bill", palette="plasma", inner="quartile") # inner='quartile' shows quartiles inside
plt.title("Total Bill Distribution by Day (Violin Plot)")
plt.xlabel("Day of the Week")
plt.ylabel("Total Bill ($)")
plt.show()

Violin plot comparing total bill distribution by day. The shape of the violins shows the density, confirming the wider spread and higher concentration of larger bills on weekends.

Violin plots give a richer understanding of the distribution's shape than standard box plots, showing multimodality if present.

Visualizing Joint Distributions

To understand the relationship between two numerical variables and their individual distributions simultaneously, we use sns.jointplot(). Let's look at total_bill versus tip.

Joint Plot (jointplot)

This function creates a scatter plot showing the relationship between the two variables in the center, with histograms (or KDEs) for each variable along the axes.

sns.jointplot(data=tips, x="total_bill", y="tip", kind="scatter", color="#37b24d") # kind='scatter' is default
plt.suptitle("Joint Distribution of Total Bill and Tip", y=1.02) # Adjust title position
plt.show()

# We can also use kind='kde' for density contours
sns.jointplot(data=tips, x="total_bill", y="tip", kind="kde", color="#7048e8")
plt.suptitle("Joint KDE of Total Bill and Tip", y=1.02)
plt.show()

Joint plot showing the relationship between total bill and tip amount. The scatter plot indicates a positive correlation, while the histograms on the margins show the individual distributions of each variable.

This practical exercise demonstrates how Seaborn's distribution plots provide powerful tools for exploring and comparing data distributions, both for single variables and relationships between variables. Experiment further by applying these plots to other numerical and categorical columns in the tips dataset or your own data.

© 2026 ApX Machine Learning