0% found this document useful (0 votes)
2 views10 pages

Introduction To Data Visualization in Python

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)
2 views10 pages

Introduction To Data Visualization in Python

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

Introduction to Data Visualization

in Python
A comprehensive guide to understanding and implementing data visualization
techniques using Matplotlib for data science applications
FUNDAMENTAL CONCEPTS

What is Data Visualization?


Definition
Data Visualization is the graphical representation of information and data using visual
elements like charts, graphs, and maps. It transforms complex datasets into visual
formats that make patterns, trends, and correlations easier to understand and interpret.

Simple Terms to Remember


Keywords: Visual Storytelling • Pattern Recognition • Data Communication • Graphical
Representation • Insight Discovery

Core Components
Data: Raw numbers, facts, or statistics to be visualized
Visual Elements: Charts, graphs, colors, shapes representing data
Context: Titles, labels, legends explaining the visualization
Insight: Understanding derived from visual patterns

Remember: "A picture is worth a thousand


data points" - Good visualization makes
complex data accessible to everyone!

Data visualization bridges the gap between raw data and human understanding, enabling faster decision-making and clearer communication of
insights across technical and non-technical audiences.
Why Data Visualization Matters
Quick Pattern Recognition
Human brain processes visuals 60,000x faster than text

Spot trends instantly


Identify outliers quickly
Recognize correlations

Better Communication
Simplifies complex information for diverse audiences

Universal language
Reduces misinterpretation
Engaging storytelling

Data-Driven Decisions
Enables faster, more informed business choices

Real-time insights
Actionable intelligence
Risk identification

Exploratory Analysis
Uncovers hidden patterns and relationships

Hypothesis testing
Data quality checks
Feature discovery

Real-world Impact: According to research, presentations using visual data are 43%
more persuasive than those without. In data science workflows, visualization is crucial
for exploratory data analysis (EDA), model evaluation, and communicating results to
stakeholders.
Types of Data Visualization
01 02 03

Comparison Visualizations Distribution Visualizations Relationship Visualizations


Compare values across categories or groups Show how data is spread across ranges Display correlations between variables

04 05

Composition Visualizations Temporal Visualizations


Illustrate parts of a whole Represent changes over time

1. Comparison Charts 4. Composition Charts


Purpose: Compare discrete values across categories Purpose: Display how parts make up a whole

Types: Bar charts, column charts, grouped bars, stacked bars Types: Pie charts, donut charts, stacked area charts, treemaps

Best for: Comparing sales across regions, product performance, survey Best for: Market share, budget allocation, demographic breakdowns
responses
Key Feature: Shows proportions and percentages clearly
Key Feature: Uses length/height to show magnitude differences
5. Temporal Charts
2. Distribution Charts
Purpose: Track changes across time periods
Purpose: Show frequency and spread of data
Types: Line graphs, area charts, time series plots, Gantt charts
Types: Histograms, box plots, violin plots, density plots
Best for: Stock prices, seasonal trends, project timelines, growth
Best for: Understanding data distribution, identifying skewness, patterns
detecting outliers
Key Feature: X-axis represents time progression
Key Feature: Reveals central tendency and variability

Exam Tip: Remember "CDRCT" - Comparison, Distribution,


3. Relationship Charts
Relationship, Composition, Temporal. Each type serves a
Purpose: Explore connections between variables specific analytical purpose!

Types: Scatter plots, bubble charts, heatmaps, correlation matrices

Best for: Finding correlations, regression analysis, clustering patterns

Key Feature: Position shows relationship strength and direction


Data Visualization in Data Science Pipeline
Data Collection
Visualize data sources and quality

Data Cleaning
Identify missing values and outliers

EDA
Explore patterns and distributions

Model Building
Visualize feature importance

Evaluation
Plot performance metrics

Communication
Present insights to stakeholders

Role in Each Phase Real-world Examples


1. Exploratory Data Analysis (EDA): Visualization is the backbone of EDA, Healthcare: Visualizing patient vitals over time to predict health
helping data scientists understand data structure, identify patterns, detect deterioration, mapping disease outbreaks geographically
anomalies, and formulate hypotheses before modeling.
Finance: Stock market candlestick charts, portfolio performance
2. Feature Engineering: Plots reveal relationships between features and target dashboards, risk heat maps for investment decisions
variables, guiding creation of new features. Correlation heatmaps and pair plots
E-commerce: Customer journey funnels, product
are invaluable here.
recommendation networks, sales trend analysis across seasons
3. Model Diagnostics: Learning curves, residual plots, and confusion matrices
Climate Science: Temperature change time series, geographical
help assess model performance, identify overfitting/underfitting, and debug
heat maps of carbon emissions, precipitation patterns
issues.

4. Results Communication: Final visualizations translate technical findings into


actionable business insights for non-technical stakeholders.
PYTHON LIBRARY

Introduction to Matplotlib
What is Matplotlib?
Matplotlib is the foundational plotting library in Python, created by John
D. Hunter in 2003. It provides a comprehensive, MATLAB-like interface
for creating static, animated, and interactive visualizations.

Keywords to Remember
MATLAB-style • Object-Oriented • Publication-Quality • Highly
Customizable • Cross-Platform

Why Matplotlib?
Industry Standard: Foundation for other libraries (Seaborn, Pandas
plotting)
Versatile: Creates any type of plot imaginable
Control: Fine-grained customization of every element
Integration: Works with NumPy, Pandas, SciPy
Output Formats: PNG, PDF, SVG, EPS for publications

Installation Commands

# Using pip
pip install matplotlib

# Using conda
conda install matplotlib

# Verify installation
python -c "import matplotlib; print(matplotlib.__version__)"

Basic Import Statement

# Standard import convention


import [Link] as plt
import numpy as np

# For Jupyter notebooks - display plots inline


%matplotlib inline

Pro Tip: The alias 'plt' is universally used in the Python community. Always import [Link] as plt for consistency with documentation and
examples.
Matplotlib Architecture & Core Concepts

Figure Axes
The entire window or page - the top-level container for all plot The plotting area with data - can have multiple axes in one figure
elements

Axis Artist
The number lines (x-axis, y-axis) that define graph boundaries Everything visible on the figure - lines, text, patches, etc.

The pyplot Module Figure & Axes Hierarchy


pyplot is Matplotlib's state-based interface that mimics
# Creating Figure and Axes explicitly
MATLAB. It provides a simple, procedural way to create plots
fig, ax = [Link]()
without explicit object management.

Two Interfaces # Figure properties


fig.set_size_inches(10, 6)
1. pyplot (Implicit): Quick and easy for simple plots, maintains fig.set_dpi(100)
current figure/axes state [Link]('Main Title')

2. Object-Oriented (Explicit): More control, better for complex


# Axes properties
plots, recommended for applications
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
Remember: Figure is the canvas, Axes is where you ax.set_title('Subplot Title')
paint, Axis is the frame! [Link](True)

Key Concept: A Figure can contain multiple Axes (subplots), but each Axes
belongs to only one Figure. This hierarchical structure enables complex multi-
panel layouts.

Basic Workflow Pattern


01 02

Import Libraries Prepare Data


Import [Link] and data libraries Create or load data arrays using NumPy/Pandas

03 04

Create Figure/Axes Plot Data


Initialize the plotting canvas Call plotting functions with data

05 06

Customize Display/Save
Add labels, titles, legends, styling Show plot or save to file
Basic Plotting with Matplotlib
1. Line Plot - Visualizing Trends

Purpose: Display continuous data, show trends over time or ordered


categories

Syntax & Example:

import [Link] as plt


import numpy as np

# Data
x = [Link](0, 10, 100)
y = [Link](x)

# Create line plot


[Link](figsize=(10, 5))
[Link](x, y, color='#325F7B',
linewidth=2, label='sin(x)')
[Link]('X values')
[Link]('Y values')
[Link]('Simple Line Plot')
[Link]()
[Link](True, alpha=0.3)
[Link]()
Use Cases: Stock prices over time, temperature changes, sales trends,
machine learning loss curves

Common Parameters: color, linewidth, linestyle ('--', '-.', ':'), marker ('o',
's', '^'), label

2. Bar Chart - Comparing Categories

Purpose: Compare discrete categories or groups

Syntax & Example:

# Data
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

# Create bar chart


[Link](figsize=(8, 6))
[Link](categories, values,
color='#51738C',
edgecolor='black', width=0.6)
[Link]('Categories')
[Link]('Values')
[Link]('Bar Chart Example')
[Link](0, 100)
[Link]()

# Horizontal bar chart


[Link](categories, values,
color='#325F7B')
Variations: Horizontal bars (barh), grouped bars, stacked bars

Use Cases: Sales by product, survey results, population by region,


model accuracy comparison

3. Histogram - Understanding Distributions

Purpose: Show frequency distribution of continuous data

Syntax & Example:

# Generate random data


data = [Link](1000)

# Create histogram
[Link](figsize=(8, 6))
[Link](data, bins=30,
color='#325F7B',
edgecolor='black',
alpha=0.7)
[Link]('Value')
[Link]('Frequency')
[Link]('Histogram - Normal Distribution')
[Link]([Link](), color='red',
linestyle='--',
label=f'Mean: {[Link]():.2f}')
[Link]()
[Link]()

Use Cases: Age distribution, exam scores, income ranges, sensor


readings, model residuals analysis
Key Parameter: bins - controls granularity (fewer bins = broader view,
more bins = detailed view)
More Basic Plots & Advanced Techniques
4. Pie Chart - Showing Composition

Purpose: Display parts of a whole as percentages

Syntax & Example:

# Data
labels = ['Category A', 'Category B',
'Category C', 'Category D']
sizes = [30, 25, 20, 25]
colors = ['#325F7B', '#51738C',
'#F6F0E4', '#8FA8B8']
explode = (0.1, 0, 0, 0) # Explode 1st slice

# Create pie chart


[Link](figsize=(8, 8))
[Link](sizes, labels=labels,
colors=colors, explode=explode,
autopct='%1.1f%%', startangle=90,
shadow=True)
[Link]('Pie Chart - Market Share')
[Link]('equal')
[Link]()

Use Cases: Budget allocation, market share, demographic composition,


survey responses
Best Practice: Use for 5-6 categories max; consider bar charts for more
categories

5. Scatter Plot - Exploring Relationships

Purpose: Visualize correlation between two variables

Syntax & Example:

# Generate data
[Link](42)
x = [Link](100) * 100
y = 2 * x + [Link](100) * 10

# Create scatter plot


[Link](figsize=(8, 6))
[Link](x, y, c='#325F7B',
s=50, alpha=0.6,
edgecolors='black')
[Link]('Variable X')
[Link]('Variable Y')
[Link]('Scatter Plot - Correlation')
[Link](True, alpha=0.3)

# Add trend line


z = [Link](x, y, 1)
p = np.poly1d(z)
Parameters: s (size), c (color), alpha (transparency), marker style
[Link](x, p(x), "r--",
linewidth=2, label='Trend') Use Cases: Feature correlation, regression analysis, clustering
[Link]() visualization, outlier detection
[Link]()

Advanced Techniques Overview

Multiple Line Plots


Plot multiple datasets on same axes for comparison

[Link](x, y1, label='Dataset 1')


1
[Link](x, y2, label='Dataset 2')
[Link](x, y3, label='Dataset 3')
[Link]()

Styling & Customization


Control colors, line styles, markers, fonts

2 [Link]('seaborn-v0_8')
[Link]['[Link]'] = 12
[Link]['[Link]'] = 100

Annotations & Text


Add arrows, text boxes, mathematical expressions

[Link]('Peak', xy=(x_peak, y_peak),


3
xytext=(x_peak+1, y_peak+5),
arrowprops=dict(arrowstyle='->'))
[Link](5, 10, r'$\alpha > \beta$')

Logarithmic Scales
Handle data spanning multiple orders of magnitude

4 [Link]('log') # Logarithmic y-axis


[Link]('log') # Logarithmic x-axis
[Link](x, y) # Both axes log scale

Error Bars
Visualize uncertainty and variability in data

[Link](x, y, yerr=error,
5
fmt='o', capsize=5,
ecolor='red',
label='Data with errors')
Subplots in Matplotlib - Advanced Layouts
Creating Subplots - Multiple Plots in One Figure

Method 1: subplot() Function Method 2: subplots() Function (Recommended)


MATLAB-style, implicit state-based approach Object-oriented approach, returns fig and axes array

# Create 2x2 grid of subplots # Create 2x2 grid - returns figure and axes
[Link](figsize=(12, 10)) fig, axes = [Link](2, 2,
figsize=(12, 10))
# First subplot (top-left)
[Link](2, 2, 1) # Access individual subplots
[Link]([1, 2, 3, 4], [1, 4, 2, 3]) axes[0, 0].plot([1, 2, 3, 4], [1, 4, 2, 3])
[Link]('Plot 1') axes[0, 0].set_title('Plot 1')

# Second subplot (top-right) axes[0, 1].bar(['A', 'B', 'C'], [3, 7, 5])


[Link](2, 2, 2) axes[0, 1].set_title('Plot 2')
[Link](['A', 'B', 'C'], [3, 7, 5])
[Link]('Plot 2') axes[1, 0].hist([Link](100),
bins=20)
# Third subplot (bottom-left) axes[1, 0].set_title('Plot 3')
[Link](2, 2, 3)
[Link]([Link](100), bins=20) axes[1, 1].scatter([Link](50),
[Link]('Plot 3') [Link](50))
axes[1, 1].set_title('Plot 4')
# Fourth subplot (bottom-right)
[Link](2, 2, 4) plt.tight_layout()
[Link]([Link](50), [Link]()
[Link](50))
[Link]('Plot 4')
Advantages: More explicit control, easier to manage multiple plots,
plt.tight_layout() better for complex layouts
[Link]()

Syntax: subplot(rows, cols, index) where index starts at 1

Layout Management & Advanced Features

Shared Axes Grid-based Layouts


Link axes across subplots for synchronized zooming/panning Create complex subplot arrangements using GridSpec

fig, (ax1, ax2) = [Link](2, 1, import [Link] as gridspec


sharex=True)
# Both plots share same x-axis fig = [Link](figsize=(12, 8))
[Link](x, y1) gs = [Link](3, 3)
[Link](x, y2)
# Span multiple cells
ax1 = fig.add_subplot(gs[0, :])
Options: sharex=True, sharey=True, or both ax2 = fig.add_subplot(gs[1, :-1])
ax3 = fig.add_subplot(gs[1:, -1])
ax4 = fig.add_subplot(gs[-1, 0])
ax5 = fig.add_subplot(gs[-1, -2])

Use case: Dashboard-style layouts with different sized panels

tight_layout() Nested Subplots


Automatically adjust spacing to prevent overlapping Create subplots within subplots for hierarchical views

plt.tight_layout() fig = [Link](figsize=(12, 8))


# Or with padding
plt.tight_layout(pad=2.0) # Main subplot
ax_main = fig.add_subplot(2, 1, 1)
ax_main.plot(data)
Alternative: Use constrained_layout=True in subplots() for automatic
management # Nested subplots in bottom half
gs = fig.add_gridspec(2, 2,
top=0.48,
bottom=0.02)
ax_sub1 = fig.add_subplot(gs[1, 0])
ax_sub2 = fig.add_subplot(gs[1, 1])

Exam Tips - Key Differences


subplot(): Use when plots are created sequentially, simpler for beginners
subplots(): Use when all plots known upfront, better for complex layouts, recommended for production code
GridSpec: Use for non-uniform layouts where subplots span multiple rows/columns

Best Practice: Always use tight_layout() or constrained_layout=True to ensure professional-looking figures with proper spacing. For publications, save
figures using [Link]('[Link]', dpi=300, bbox_inches='tight').

You might also like