0% found this document useful (0 votes)
20 views35 pages

Data Visualization with Python Libraries

Chapter 3 covers data visualization techniques using Python libraries such as Pandas, Matplotlib, and Seaborn. It includes topics on data manipulation, handling missing data, dimensionality reduction, and various types of visualizations like line plots, bar charts, and heatmaps. The chapter emphasizes the ease of use and integration of these libraries with data analysis workflows.

Uploaded by

lntan291101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views35 pages

Data Visualization with Python Libraries

Chapter 3 covers data visualization techniques using Python libraries such as Pandas, Matplotlib, and Seaborn. It includes topics on data manipulation, handling missing data, dimensionality reduction, and various types of visualizations like line plots, bar charts, and heatmaps. The chapter emphasizes the ease of use and integration of these libraries with data analysis workflows.

Uploaded by

lntan291101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 3 – DATA VISUALIZATION

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 1


CONTENTS

3.1 • PANDAS
3.2 • MISSING DATA
3.3 • CLEANED AND TRANSFORMED DATA
3.4 • DIMENSIONALITY REDUCTION
3.5 • MATPLOTLIB & SEABORN
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 2
3.1 PANDAS

• Pandas is a powerful Python library for data manipulation


and analysis.
• It provides data structures such as Series and DataFrame.
• Built on top of NumPy and integrates well with other
libraries.
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 3
3.1 PANDAS

# Install Pandas
!pip install pandas
import pandas as pd

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 4


3.1 PANDAS
Pandas DataFrame
# Creating a DataFrameimport pandas as pd
data = { 'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago’]}
df = [Link](data)
print(df)
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 5
3.1 PANDAS
Accessing Data in DataFrame
# Accessing a column
print(df[‘Name’])
# Accessing a row
print([Link][0])
# Accessing multiple columns
print(df[['Name', 'Age']])
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 6
3.1 PANDAS
Transforming DataFrame
# Adding a New Column
df['Salary'] = [50000, 60000, 70000] → print(df)
# Filtering Data
# Filtering rows where Age > 28
filtered_df = df[df['Age'] > 28] → print(filtered_df)

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 7


3.1 PANDAS
Transforming DataFrame
# Sorting Data
sorted_df = df.sort_values (by='Age’, ascending=False)
print(sorted_df)
# Grouping Data
grouped =[Link]('City')['Age'].mean()
print(grouped)
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 8
3.2 MISSING DATA
Checking missing data
missing_locs =
print([Link]().sum()) [Link]().stack()[[Link]().stack()].index
Filling Missing Values
# Filling missing values with a specific value
[Link](value=0, inplace=True)
print(df)
# Filling missing values with the column mean/median
df['Age'].fillna(df['Age'].mean/median(), inplace=True)
print(df)
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 9
3.2 MISSING DATA
Dropping Missing Values
# Dropping rows with missing values
[Link](inplace=True)
print(df)
# Dropping columns with missing values
[Link](axis=1, inplace=True)
print(df)

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 10


3.2 MISSING DATA
Interpolating Missing Data
# Using interpolation to estimate missing values
[Link](inplace=True)
print(df)

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 11


3.3 CLEANED AND TRANSFORMED DATA
Removing Duplicates
# Dropping duplicate rows
df.drop_duplicates(inplace=True)
print(df)
Renaming Columns
# Renaming columns
[Link](columns={'Name': 'Full Name', 'Age': 'Years'}, inplace=True)
print(df)
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 12
3.3 CLEANED AND TRANSFORMED DATA
Normalizing Data
# Normalizing Age column (min-max scaling)
df['Years'] = (df['Years'] - df['Years'].min()) / (df['Years'].max() - df['Years'].min())
print(df)
Encoding Categorical Variables
# Encoding categorical data using one-hot encoding
df = pd.get_dummies(df, columns=['City’])
print(df)
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 13
3.4 DIMENSIONALITY REDUCTION
Principal Component Analysis (PCA)
from [Link] import PCA
from [Link] import StandardScaler
# Standardizing the data
scaler = StandardScaler()
df_scaled = scaler.fit_transform(df.select_dtypes(include=['number’]))
# Applying PCApca = PCA(n_components=2)
df_pca = pca.fit_transform(df_scaled)
print(df_pca)
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 14
3.4 DIMENSIONALITY REDUCTION
Feature Selection Using Variance Threshold
from sklearn.feature_selection import VarianceThreshold
# Removing low-variance features
selector = VarianceThreshold(threshold=0.1)
df_reduced = selector.fit_transform(df.select_dtypes(include=['number’]))
print(df_reduced)

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 15


3.5 MATPLOTLIB

• Matplotlib is a popular Python library for data visualization.


• It provides various types of plots, including line plots, bar charts,
histograms, and scatter plots.
• It is highly customizable and integrates well with NumPy and
Pandas.
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 16
3.5 MATPLOTLIB
# Install Matplotlib if not already installed
!pip install matplotlib
import [Link] as plt

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 17


3.5 MATPLOTLIB
Creating a Line Plot
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
[Link](x, y)[Link]('X-axis’)
[Link]('Y-axis’)
[Link]('Simple Line Plot’)
[Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 18
3.5 MATPLOTLIB
Customizing a Line Plot
[Link](x, y, marker='o', linestyle='--', color='r', linewidth=2)
[Link]('X-axis’)
[Link]('Y-axis’)
[Link]('Customized Line Plot’)
[Link](True)
[Link]()

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 19


3.5 MATPLOTLIB
Customizing a Line Plot
[Link]

[Link]

[Link]

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 20


3.5 MATPLOTLIB
Creating a Bar Chart
categories = ['A', 'B', 'C', 'D’]
values = [3, 7, 1, 8]
[Link](categories, values, color=['blue', 'green', 'red', 'purple’])
[Link]('Categories’)
[Link]('Values’)
[Link]('Bar Chart Example’)
[Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 21
3.5 MATPLOTLIB
Creating a Histogram
import numpy as np
data = [Link](1000)
[Link](data, bins=30, color='skyblue', edgecolor='black’)
[Link]('Value’)
[Link]('Frequency’)
[Link]('Histogram Example’)
[Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 22
3.5 MATPLOTLIB
Creating a Scatter Plot

x = [Link](50)
y = [Link](50)
colors = [Link](50)
[Link](x, y, c=colors, cmap='viridis', edgecolors='black’)
[Link]('X-axis’)
[Link]('Y-axis’)
[Link]('Scatter Plot Example’)
[Link](label='Color Scale’) → [Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 23
3.5 MATPLOTLIB
Creating a Pie Chart

labels = ['Apple', 'Banana', 'Cherry', 'Date’]


sizes = [15, 30, 45, 10]
colors = ['red', 'yellow', 'pink', 'brown’]
[Link](sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
[Link]('Pie Chart Example’)
[Link]()

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 24


3.5 MATPLOTLIB
Subplots in Matplotlib

fig, axs = [Link](2, 2, figsize=(10, 8))


# First subplot
t = [Link](0, 2*[Link], 100)
axs[0, 0].plot(t, [Link](t))
axs[0, 0].set_title('Sine Wave’)
# Second subplot
axs[0, 1].plot(t, [Link](t), 'r’)
axs[0, 1].set_title('Cosine Wave')
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 25
3.5 MATPLOTLIB
Subplots in Matplotlib

# Third subplot
axs[1, 0].hist([Link](1000), bins=20, color='purple’)
axs[1, 0].set_title('Histogram’)
# Fourth subplotcategories = ['A', 'B', 'C', 'D’]
values = [3, 7, 1, 8]
axs[1, 1].bar(categories, values, color=['blue', 'green', 'red', 'purple’])
axs[1, 1].set_title('Bar Chart’)
plt.tight_layout() → [Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 26
3.5 MATPLOTLIB

Summary
•Line Plots: Useful for trend visualization.
•Bar Charts: Good for categorical comparisons.
•Histograms: Show data distributions.
•Scatter Plots: Display relationships between variables.
•Pie Charts: Represent proportions.
•Subplots: Enable multiple visualizations in one figure.
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 27
3.5 SEABORN

• Seaborn is a Python data visualization library based on Matplotlib.


• High-level interface for drawing and informative statistical graphics.
• Seaborn works well with Pandas DataFrames and NumPy arrays.

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 28


3.5 SEABORN
Feature Seaborn Matplotlib
High-level API for statistical Low-level, general-purpose
Purpose
data visualization plotting library
Simplifies complex Requires more code for
Ease of Use
visualizations customization
Works with arrays but
Works seamlessly with
Integration requires more effort for
Pandas DataFrames
Pandas
Comes with attractive default Requires manual styling for
Default Styling
themes aesthetic improvements
Specialized statistical plots
Basic charts like line, bar, and
Plot Types like violin plots, pair plots,
scatter plots
and heatmaps
Easier for high-level Offers more detailed, fine-
Customization
statistical visualization grained control
Built on Matplotlib but
Generally more performant
Performance optimized for dataset-level
for simple plots
operations
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 29
3.5 SEABORN

Installing Seaborn
# Install Seaborn if not already installed
!pip install seaborn
import seaborn as sns
import [Link] as plt

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 30


3.5 SEABORN

Creating a Basic Scatter Plot


import seaborn as sns
# Load built-in dataset
df = sns.load_dataset('tips’)
print([Link]())

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 31


3.5 SEABORN

Creating a Basic Scatter Plot


import seaborn as sns
# Load built-in dataset
df = sns.load_dataset('tips’) → print([Link]())
[Link](x='total_bill', y='tip', data=df)
[Link]('Scatter Plot of Total Bill vs Tip’)
[Link]()

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 32


3.5 SEABORN

Creating a Line Plot


[Link](x='size', y='total_bill', data=df, marker='o’)
[Link]('Line Plot Example’)
[Link]()
Creating a Bar Plot
[Link](x='day', y='total_bill', data=df, ci=None, palette='muted’)
[Link]('Bar Plot Example’)
[Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 33
3.5 SEABORN

Creating a Box Plot


[Link](x='day', y='total_bill', data=df, palette='coolwarm’)
[Link]('Box Plot Example’)
[Link]()

TS. NGUYỄN ANH TÚ – HUB 20/10/2025 34


3.5 SEABORN

Creating a Heatmap
import numpy as np corr = [Link]()
[Link](corr, annot=True, cmap='coolwarm', linewidths=0.5)
[Link]('Heatmap of Correlation Matrix’) → [Link]()

Pair Plot for Multivariate Analysis


[Link](df, hue='sex', palette='husl’)
[Link]()
TS. NGUYỄN ANH TÚ – HUB 20/10/2025 35

You might also like