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

Box Plots for Categorical Variables (boxplot)

Bar plots typically show the central tendency (like the mean or median) for a numerical variable across different categories, but they often do not fully represent how data is spread out within each category. Understanding if values are tightly clustered or widely dispersed, and identifying outliers, requires a different visualization. Box plots are effective for visualizing and comparing overall data distributions to answer these questions about data spread and outliers.

A box plot (or box-and-whisker plot) provides a concise visual summary of a dataset's distribution. It displays five important statistics:

  1. Median (Q2): The middle value of the data (50th percentile), represented by a line inside the box.
  2. First Quartile (Q1): The value below which 25% of the data falls (25th percentile). This is the bottom edge of the box.
  3. Third Quartile (Q3): The value below which 75% of the data falls (75th percentile). This is the top edge of the box.
  4. Interquartile Range (IQR): The range between Q1 and Q3 (IQR = Q3 - Q1). The box itself represents the IQR, containing the middle 50% of the data.
  5. Whiskers: Lines extending from the box, typically showing the range of the data within 1.5 times the IQR from Q1 and Q3. Points outside the whiskers are often treated as potential outliers and plotted individually.

Seaborn's boxplot function is specifically designed to create these visualizations, making it easy to compare distributions across different categories.

Creating Box Plots with seaborn.boxplot

The basic syntax involves specifying the categorical variable for one axis (usually x), the numerical variable for the other axis (usually y), and the DataFrame containing the data using the data parameter.

Let's use the familiar 'tips' dataset that comes with Seaborn. We can compare the distribution of total bill amounts for each day of the week.

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

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

# Create the box plot
plt.figure(figsize=(8, 5)) # Adjust figure size for better readability
sns.boxplot(x="day", y="total_bill", data=tips, palette=["#74c0fc", "#ffc078", "#8ce99a", "#ffc9c9"])

# Add title and labels (optional but recommended)
plt.title("Distribution of Total Bill Amounts by Day")
plt.xlabel("Day of the Week")
plt.ylabel("Total Bill ($)")

# Show the plot
plt.show()

Distribution of total bill amounts across different days of the week using Seaborn's boxplot.

Interpreting the Box Plot

From the plot above, we can draw several observations:

  • Median: The line inside each box shows the median total bill. Saturdays and Sundays tend to have higher median bills than Thursdays and Fridays.
  • Spread (IQR): The height of the box (IQR) indicates the spread of the middle 50% of bills. Saturdays seem to have a larger IQR, suggesting more variability in bill amounts compared to Thursdays.
  • Whiskers: The whiskers show the range of typical bills. Weekend days (Saturday, Sunday) appear to have a wider range, extending to higher values.
  • Outliers: Individual points plotted outside the whiskers represent potential outliers. Sundays and Saturdays show several high-value outliers, indicating some exceptionally large bills on those days. Thursday also has one quite high outlier.

Compared to a bar plot showing only the average bill per day, the box plot gives us a much richer understanding of how bill amounts vary within each day.

Customizing Box Plots

Like other Seaborn functions, boxplot offers various customization options.

  • Orientation: You can create horizontal box plots by swapping x and y or setting orient='h'.

    # Horizontal box plot
    sns.boxplot(x="total_bill", y="day", data=tips, orient='h', palette=["#74c0fc", "#ffc078", "#8ce99a", "#ffc9c9"])
    plt.title("Distribution of Total Bill Amounts by Day")
    plt.xlabel("Total Bill ($)")
    plt.ylabel("Day of the Week")
    plt.show()
    
  • Order: Control the order in which categories appear using the order parameter, passing a list of category names.

    # Specify order of days
    day_order = ["Thur", "Fri", "Sat", "Sun"]
    sns.boxplot(x="day", y="total_bill", data=tips, order=day_order, palette=["#74c0fc", "#ffc078", "#8ce99a", "#ffc9c9"])
    # ... (add titles/labels and show plot)
    
  • Hue: You can add another categorical dimension using the hue parameter, which creates separate, side-by-side boxes for each level of the hue variable within each main category on the x-axis. For example, you could compare bills by day, split by whether the customer was a smoker.

    # Add 'smoker' as a hue dimension
    sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="pastel")
    plt.title("Distribution of Total Bill by Day and Smoker Status")
    plt.xlabel("Day of the Week")
    plt.ylabel("Total Bill ($)")
    plt.show()
    

Box plots are particularly effective when you want to compare the distributions of a numerical variable across several groups defined by one or more categorical variables. They provide a quick way to assess differences in central tendency, spread, and the presence of outliers between the groups.

  • seaborn.boxplot, Seaborn Developers, 2024 - Official documentation for Seaborn's boxplot function, detailing its parameters and usage.
  • Python for Data Analysis: Data Wrangling with pandas, NumPy, and IPython, Wes McKinney, 2022 (O'Reilly Media) - A practical guide to data manipulation and visualization in Python using libraries like Pandas, Matplotlib, and Seaborn.
  • An Introduction to Statistical Learning: With Applications in Python, Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani, Jonathan Taylor, 2023 (Springer) DOI: 10.1007/978-3-031-38747-0 - Provides a comprehensive statistical foundation for data analysis and visualization, including the principles behind box plots.

© 2026 ApX Machine Learning