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

Filtering and Preparing Data for Plotting

Often, the raw data you load into a Pandas DataFrame isn't immediately ready for visualization. You might have more columns than needed for a specific plot, or you might only want to visualize a subset of the rows that meet certain criteria. Preparing your data involves selecting the relevant pieces and filtering out the noise, ensuring your plots communicate the intended message clearly.

Selecting Specific Columns

DataFrames can contain many columns, but a single plot usually only visualizes relationships between two or three variables. You can easily select the columns you need using bracket notation.

To select a single column (which returns a Pandas Series), use single brackets:

# Assume 'df' is your DataFrame
product_names = df['ProductName']
sales_data = df['Sales']

To select multiple columns (which returns a new DataFrame), use a list of column names inside double brackets:

# Select 'ProductName' and 'Sales' columns
product_sales_df = df[['ProductName', 'Sales']]

# Display the first few rows of the new DataFrame
print(product_sales_df.head())

This product_sales_df now contains only the data needed for, perhaps, a bar chart showing sales per product, making it easier to pass to plotting functions.

Filtering Rows Based on Conditions

Just as you might only need specific columns, you often only want to visualize rows that meet certain conditions. This is frequently called boolean indexing or conditional selection. You create a condition (which evaluates to True or False for each row) and use it inside the brackets to filter the DataFrame.

Example 1: Simple Condition

Let's say you have a DataFrame df with sales data and you only want to plot products with sales greater than 100010001000.

# Create a boolean Series: True for rows where Sales > 1000, False otherwise
high_sales_condition = df['Sales'] > 1000

# Use the boolean Series to filter the DataFrame
high_sales_df = df[high_sales_condition]

# Or, more concisely:
high_sales_df = df[df['Sales'] > 1000]

# Now, high_sales_df contains only rows meeting the condition
print(high_sales_df.head())

You can then use high_sales_df for plotting.

Example 2: Multiple Conditions

You can combine conditions using logical operators: & for AND, | for OR. It's important to wrap each individual condition in parentheses () due to Python's operator precedence rules.

Suppose you want to visualize data for products in the 'Electronics' category and with sales above 500500500.

# Condition 1: Category is 'Electronics'
condition1 = df['Category'] == 'Electronics'
# Condition 2: Sales are greater than 500
condition2 = df['Sales'] > 500

# Combine conditions using AND (&)
# Note the parentheses around each condition
electronics_high_sales_df = df[(condition1) & (condition2)]

# Or, directly:
electronics_high_sales_df = df[(df['Category'] == 'Electronics') & (df['Sales'] > 500)]

print(electronics_high_sales_df)

Similarly, to select 'Electronics' or products with sales above 150015001500:

# Combine conditions using OR (|)
relevant_products_df = df[(df['Category'] == 'Electronics') | (df['Sales'] > 1500)]

print(relevant_products_df)

Filtering allows you to focus your visualizations on specific segments of your data, making your plots more targeted and insightful.

Handling Missing Data (Basic Approach)

"Datasets often contain missing values, represented in Pandas as NaN (Not a Number). Plotting functions might behave unexpectedly or produce errors when encountering NaNs."

A simple strategy for dealing with missing data before plotting is to remove rows that have missing values in the columns you intend to plot. The .dropna() method is useful here.

# Assume we want to plot 'Sales' vs 'Profit'
# Check for missing values in these columns
print(df[['Sales', 'Profit']].isnull().sum())

# Drop rows where *either* 'Sales' or 'Profit' is NaN
cleaned_df = df.dropna(subset=['Sales', 'Profit'])

# Verify missing values are handled (output should be 0 for these columns)
print(cleaned_df[['Sales', 'Profit']].isnull().sum())

Now, cleaned_df can be used for plotting without issues caused by missing values in the 'Sales' or 'Profit' columns. Be aware that removing rows means discarding data, which might not always be the best approach, but it's a reasonable starting point for basic visualization preparation.

Putting It Together: Filtering for a Plot

Let's combine these ideas. Imagine you have a DataFrame customer_df with columns 'Age', 'City', 'SpendingScore'. You want to create a scatter plot of 'Age' vs 'SpendingScore' but only for customers from 'New York' who are younger than 40.

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

# Sample DataFrame (replace with loading your actual data)
data = {'Age': [25, 45, 35, 50, 22, 38, 60],
        'City': ['New York', 'Los Angeles', 'New York', 'Chicago', 'New York', 'Chicago', 'New York'],
        'SpendingScore': [75, 50, 85, 40, 90, 45, 60]}
customer_df = pd.DataFrame(data)

# 1. Filter the data
filtered_customers = customer_df[(customer_df['City'] == 'New York') & (customer_df['Age'] < 40)]

# Display the filtered data
print("Filtered Data for Plotting:")
print(filtered_customers)

# 2. Create the plot using the filtered data
plt.figure(figsize=(8, 5)) # Set figure size
sns.scatterplot(data=filtered_customers, x='Age', y='SpendingScore')
plt.title('Spending Score vs. Age (New York Customers < 40)')
plt.xlabel('Age')
plt.ylabel('Spending Score')
plt.grid(True) # Add grid for readability
plt.show()

By first filtering the DataFrame to include only the rows of interest (filtered_customers), the subsequent scatter plot specifically visualizes the relationship within that subgroup. Attempting to plot the entire customer_df and then mentally filtering would be much less effective.

Preparing your data using Pandas selection and filtering techniques is a common preliminary step in the data visualization workflow. It ensures that your plots are based on the correct subset of your data, leading to clearer and more accurate insights.

  • Pandas User Guide: Indexing and selecting data, The Pandas Development Team, 2024 - Provides authoritative guidance on selecting columns and filtering rows using various Pandas methods, including boolean indexing.
  • Pandas User Guide: Working with missing data, The Pandas Development Team, 2024 - Details how to identify and handle missing values in DataFrames, specifically covering the dropna() method used for data preparation.
  • Python for Data Analysis, Wes McKinney, 2022 (O'Reilly Media) - The definitive book on data manipulation with Pandas, covering data selection, filtering, and missing data handling comprehensively. (3rd edition)
  • Effective Pandas: A Guide to Using the Python Data Analysis Library, Matt Harrison, 2021 (O'Reilly Media) - A practical guide offering best practices and efficient techniques for common Pandas operations like selecting, filtering, and cleaning data.

© 2026 ApX Machine Learning