Introduction to Data Visualization in Python
What is Data Visualization?
Let’s say you have a big list of numbers like this:
Marks = [89, 67, 90, 45, 92, 78, 56, 85, 70, 60]
You ask your students:
“How many students scored above 80?”
They’ll say: “Wait wait… let me count… uhh… wait… 1… 2…”
That’s painful 😩
Now you draw a graph 📈 — boom! In 2 seconds they say:
“Oh yeah! Looks like 4–5 students scored above 80!”
🎯 That’s the power of Data Visualization.
Definition:
Data Visualization is the process of converting numbers, tables, and
complex data into meaningful visuals (like charts and plots) so that it's easier to
understand, analyze, and communicate.
Why Do We Need Data Visualization as a Data Analyst?
Let’s make it clear. If you are a data analyst, then you’re basically the "Data
Detective".
But imagine trying to solve a crime just by reading boring police files... or
watching CCTV footage that directly shows the suspect enter?
✅ Visualization = CCTV of Data
Here’s exactly why we need it:
Reason Explanation
🧠 Quick Understanding Human brain processes visuals 60,000x faster than text
📈 Spot Patterns See trends, peaks, or drops easily
📊 Compare Categories Like sales per product or score per subject
🚩 Find Outliers Visuals show weird data instantly
🗣️ Tell Stories Help others (non-technical people) understand data
⚙️ Validate Analysis Quickly verify if results make sense
💼 Real-World Scenarios Where You’ll Use Plots
Situation Visualization
Sales over months Line chart
Students performance Bar chart
Gender ratio Pie chart
Marks vs attendance Scatter plot
Score distribution Histogram
Salary outliers Box plot
Why Python for Visualization?
Python gives you powerful libraries like:
● Matplotlib (low-level, flexible)
● Seaborn (advanced, clean, built on matplotlib)
● Plotly (interactive)
We’ll start with Matplotlib first — the foundation of all others.
[Link] – Your Drawing Board
Just like math has sqrt(),
matplotlib has pyplot – a submodule where all the plotting magic lives.
Before using it:
import [Link] as plt
You’ll always use [Link]() to make graphs.
Most Common Parameters in Matplotlib Charts
Let’s build a reference table of parameters that work across almost all charts.
Function / Param Purpose / Use
[Link](x, y) / [Link]() Create line, bar, etc.
x, y Axis variables
label= Adds name to line/bar for legend
color= / c= Change color
marker= Add marker shape (dot, triangle, square...)
linestyle= Solid, dashed, dotted line
linewidth= Thickness of line
alpha= Transparency (0 to 1)
title() Chart title
xlabel() Label for x-axis
ylabel() Label for y-axis
legend() Show legend (use with label)
grid() Add grid lines
xticks(rotation=) Rotate labels if overlapping
figsize=(x,y) Resize the entire figure
show() Show the plot window
Example:
[Link](x, y, color="green", marker="o", linestyle="--", label="Data Line")
[Link]("Sales over Time")
[Link]("Month")
[Link]("Revenue")
[Link]()
[Link]()
[Link]()
Summary
Data Visualization is not just for looking pretty.
It is a weapon in the hands of a Data Analyst to:
● Convince clients
● Prove your insights
● Explore data
● Solve real-world problems
Quote of the Day:
“If you can’t see the data, you won’t understand the story.”
1. What is a Bar Plot?
Simple Definition:
A bar plot is a chart that uses rectangles (bars) to represent and compare values across
different categories.
The length (or height) of the bar tells us the value.
Real Life Example:
Let’s say you surveyed students from 4 departments to check how many are learning
Python.
Department Count
CS 40
IT 35
ECE 20
Mech 15
Instead of printing this boring table, you draw bars →
now in one second, anyone can say:
“Ohh! CS has the most Python learners!”
That’s bar plot magic.
2. When Do We Use a Bar Plot?
✅ When comparing values of different groups
✅ When your X-axis is categorical (like names, cities, products)
✅ When you want to show ranking or differences clearly
Works Great For... Example
Categorical vs Numerical Dept vs Student Count
Frequencies Product sales, Gender counts
Comparisons Revenue by region
3. Basic Syntax
[Link](x, height)
● x = labels or categories
● height = corresponding values (numbers)
Example:
departments = ['CS', 'IT', 'ECE', 'Mech']
students = [40, 35, 20, 15]
[Link](departments, students)
[Link]()
4. All-In-One Example (With All Major Parameters)
import [Link] as plt
departments = ['CS', 'IT', 'ECE', 'Mech']
students = [40, 35, 20, 15]
[Link](figsize=(8,5)) # Resize the plot
[Link](
x=departments,
height=students,
color='skyblue', # Fill color
width=0.6, # Bar width
align='center', # Align bars in center of ticks
edgecolor='black', # Border color
linewidth=2, # Border thickness
alpha=0.9, # Transparency
label='Python Learners' # Legend name
)
[Link]("Python Learners by Department")
[Link]("Departments")
[Link]("No. of Students")
[Link]()
[Link](axis='y') # Horizontal grid lines
[Link]()
Explanation of What Happened
Line What It Did
figsize=(8,5) Resized the plot window
bar() Plotted bars for each department
color='skyblue' Gave light blue color to bars
width=0.6 Made bars thinner
align='center' Bars sit at center of tick labels
edgecolor='black' Added border around bars
linewidth=2 Made the border thick
alpha=0.9 Made bars slightly transparent
label='Python Learners' This name shows in the legend
legend() Shows the label box
grid(axis='y') Only draws horizontal grid lines (not vertical)
BONUS – Annotate the Bars
You can show exact values on top of the bars!
for i in range(len(students)):
[Link](departments[i], students[i]+0.5, str(students[i]), ha='center')
Horizontal Bar Plot – [Link]()
What is a Horizontal Bar Plot?
A horizontal bar plot is just like a regular bar plot,
but the bars go sideways (from left to right) instead of bottom to top.
Think of it like:
You're still comparing values, just rotating the view to make it more readable
for wide category names or when vertical space is tight.
When Should You Use barh() Instead of bar()?
Situation Use bar() Use barh()
Short category names ✅ ❌
Long category names ❌ ✅
More vertical space ✅ ❌
More horizontal space ❌ ✅
Want a different visual perspective ❌ ✅
🎓 Real Example:
You surveyed students from different departments about Python learning:
departments = ['CS', 'IT', 'ECE', 'Mech']
students = [40, 35, 20, 15]
Code with Full Styling:
import [Link] as plt
departments = ['CS', 'IT', 'ECE', 'Mech']
students = [40, 35, 20, 15]
[Link](figsize=(8, 5))
[Link](
y=departments,
width=students,
color='orange',
edgecolor='black',
linewidth=2,
alpha=0.85,
label='Python Learners' )
[Link]("Python Learners by Department (Horizontal View)")
[Link]("No. of Students")
[Link]("Departments")
[Link]()
[Link](axis='x')
# Add numbers next to bars
for i in range(len(students)):
[Link](students[i] + 0.5, departments[i], str(students[i]), va='center')
plt.tight_layout()
[Link]()
Output Breakdown:
● Bars go left to right (horizontal)
● X-axis shows values (student count)
● Y-axis shows departments
● Bar color is orange
● Borders around each bar are black with thickness
● Each bar shows the exact count on its right
● Grid lines help with readability
● Everything is styled professionally
✅ Why Use This in Real Life?
● To compare categories with long names
● For dashboards where horizontal space is more useful
● When vertical stacking is not readable
GROUPED BAR PLOT
What is a Grouped Bar Plot?
It’s like a regular bar plot, but instead of one bar per category, we show multiple
bars side-by-side within the same category.
Use it when you want to compare multiple things within each category.
Real-Life Example:
Department Python SQL
CS 40 35
IT 38 30
ECE 25 20
Mech 15 10
CODE:
import [Link] as plt
import numpy as np
# Data
departments = ['CS', 'IT', 'ECE', 'Mech']
python_learners = [40, 38, 25, 15]
sql_learners = [35, 30, 20, 10]
# X-axis positions
x = [Link](len(departments)) # [0, 1, 2, 3]
width = 0.35 # Width of each bar
# Plotting
[Link](figsize=(10, 6))
# Bar plots
[Link](x - width/2, python_learners, width, label='Python', color='skyblue',
edgecolor='black')
[Link](x + width/2, sql_learners, width, label='SQL', color='orange',
edgecolor='black')
# Labels and title
[Link]("Departments")
[Link]("No. of Students")
[Link]("Python vs SQL Learners by Department")
[Link](x, departments) # Label x-axis with department names
[Link]()
[Link](axis='y')
# Annotate bars
for i in range(len(x)):
[Link](x[i] - width/2, python_learners[i] + 0.5, str(python_learners[i]),
ha='center')
[Link](x[i] + width/2, sql_learners[i] + 0.5, str(sql_learners[i]), ha='center')
plt.tight_layout()
[Link]()
PARAMETER EXPLANATION:
Part What It Does
x = [Link](len(departments)) Creates base x positions for bars (like 0,1,2,3)
width = 0.35 Sets how thick the bars are
x - width/2 Positions Python bars a little to the left
x + width/2 Positions SQL bars a little to the right
label='Python' Used in the legend
xticks(x, departments) Converts 0,1,2,3 to 'CS','IT','ECE','Mech'
[Link]() Annotates the bars with numbers
color, edgecolor Visual styling
✅ Why Use Grouped Bar Plot?
● To compare multiple things inside a single category
● To see differences between subgroups
● For clean visual comparisons like:
○ Male vs Female
○ Product A vs Product B
○ Before vs After
LINE CHART – The Story of Time and Trend
What is a Line Chart?
A Line Chart connects dots with lines.
Each point shows a value, and the line shows how that value changes over time or
order.
Imagine tracking your daily mood, stock prices, or sales per month — One
smooth line tells the story beautifully.
When Should You Use Line Charts?
Use Case Why Line Chart?
Tracking values over time It shows trends clearly
Monthly sales Easy to spot growth or drop
Daily temperatures Perfect for continuous data
Comparing trends Use multiple lines to compare
Real-Life Scenario:
Let’s say you’re a data analyst in a retail store.
You’re tracking monthly sales for Python books and SQL books.
Month Python Sales SQL Sales
Jan 100 90
Feb 120 95
Mar 150 110
Apr 180 130
May 200 150
You want to visualize how sales are increasing over time.
Code:
import [Link] as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
python_sales = [100, 120, 150, 180, 200]
sql_sales = [90, 95, 110, 130, 150]
[Link](figsize=(10, 5))
[Link](months, python_sales, marker='o', color='blue', label='Python Sales',
linestyle='-')
[Link](months, sql_sales, marker='s', color='green', label='SQL Sales',
linestyle='--')
[Link]("Monthly Sales of Python vs SQL Books")
[Link]("Months")
[Link]("Sales")
[Link](True)
[Link]()
plt.tight_layout()
[Link]()
PARAMETER EXPLANATION:
Param What It Does
[Link](x, y) Draws the line from points
marker='o' Adds circle on each point
marker='s' Adds square marker (for SQL)
color='blue' Sets line color
linestyle='-' Solid line (Python)
linestyle='--' Dashed line (SQL)
legend() Shows label in a box
grid() Adds background lines
tight_layout() Adjusts spacing perfectly
What’s happening in this chart?
● X-axis → Months (Jan to May)
● Y-axis → Sales Count
● 🔵 Blue Line:
○ Shows Python book sales
○ Solid line with circular markers o
● 🟢 Green Line:
○ Shows SQL book sales
○ Dashed line with square markers s
● Clear title, axis labels, grid, and legend
This chart tells the story:
📚 Both Python and SQL book sales are rising steadily month by month —
but Python is 🔼 leading!
fill_between() - Area chart
The area chart is the same as the Line chart but the only difference is this fill_between().
If we are using fill_between(), the areas will be shaded and look like an Area chart.
Let’s see the sample code below.
import [Link] as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
python_sales = [100, 120, 150, 180, 200]
sql_sales = [90, 95, 110, 130, 150]
[Link](figsize=(10, 5))
# Plot the lines
[Link](months, python_sales, color='blue', label='Python Sales')
[Link](months, sql_sales, color='green', label='SQL Sales')
# Fill between lines and x-axis
plt.fill_between(months, python_sales, color='blue', alpha=0.3)
plt.fill_between(months, sql_sales, color='green', alpha=0.3)
[Link]("Monthly Sales with Fill Between")
[Link]("Months")
[Link]("Sales")
[Link]()
[Link](True)
plt.tight_layout()
[Link]()
OUTPUT
SCATTER PLOT – The Dots That Speak Truth
What is a Scatter Plot?
A scatter plot shows data as individual points (dots) on a graph.
Each point has:
● an X value (horizontal)
● a Y value (vertical)
There’s no connecting line like in a line chart.
Each point stands alone — showing distribution, relationships, and patterns
between two things.
Real-Life Example
You're a data analyst at an EdTech company. You want to check:
“Do students who spend more hours practicing Python score higher?”
So you collect this data:
Hours Spent Score
2 50
3 60
4 65
5 70
6 80
7 85
Now you want to visualize if there's a relationship — and how strong it is.
When Should You Use a Scatter Plot?
Use Case Reason
Check correlation Are X and Y connected?
Identify outliers Some points don’t follow the pattern
Compare variables Are higher hours giving higher results?
Explore distribution How values are spread out
Code:
import [Link] as plt
# Data
hours = [2, 3, 4, 5, 6, 7]
scores = [50, 60, 65, 70, 80, 85]
[Link](figsize=(8, 5))
[Link](hours, scores, color='purple', s=100, edgecolor='black', marker='o',
alpha=0.8)
[Link]("Practice Hours vs Score")
[Link]("Hours Spent on Practice")
[Link]("Score in Python Test")
[Link](True)
plt.tight_layout()
[Link]()
PARAMETER EXPLANATION:
Param Meaning
scatter(x, y) Creates the dot chart
color='purple' Color of dots
s=100 Size of dots
edgecolor='black' Border color of each point
marker='o' Shape of the marker
alpha=0.8 Transparency level (1 = solid, 0 = invisible)
grid(True) Adds background grid lines
Goal: Multiple Categories in One Scatter Plot
Scenario:
You now have data from two courses:
● Python Students
● SQL Students
Each group has:
● How many hours they practiced
● What score they got
You want to plot both in the same graph, but in different colors and shapes — so
it's easy to compare.
Sample Data:
Student Type Hours Score
Python 2 50
Python 3 60
Python 4 65
SQL 2 45
SQL 3 55
SQL 4 60
Code:
import [Link] as plt
# Data
python_hours = [2, 3, 4]
python_scores = [50, 60, 65]
sql_hours = [2, 3, 4]
sql_scores = [45, 55, 60]
[Link](figsize=(8, 5))
# Python students – purple circles
[Link](python_hours, python_scores, color='purple', label='Python
Students',
s=100, edgecolor='black', marker='o', alpha=0.8)
# SQL students – green squares
[Link](sql_hours, sql_scores, color='green', label='SQL Students',
s=100, edgecolor='black', marker='s', alpha=0.8)
# Labels, legend, grid
[Link]("Practice Hours vs Score – Python vs SQL Students")
[Link]("Hours Spent")
[Link]("Test Score")
[Link]()
[Link](True)
plt.tight_layout()
[Link]()
What You See:
● Purple Circles → Python Students
● Green Squares → SQL Students
● Each shape shows how that group performed over hours
● Python students scored slightly higher overall.
● Grid, legend, and axis labels for complete clarity
PARAM EXPLAINED:
Param Used For
marker='o' Circle for Python
marker='s' Square for SQL
label='...' Used in legend
color='...' Different for each group
s=100 Dot size
alpha=0.8 Transparency
edgecolor='black' Clean border for visibility
PIE CHART
What is a Pie Chart?
Imagine your data as a pizza 🍕.
Each slice of the pizza represents a portion of the total — like how many students are
learning Python, SQL, Excel, etc.
So, a Pie Chart is a circular graph where:
● The whole pie represents 100%
● Each slice shows a part of the whole
“It’s the chart that makes data easy to digest.”
When to Use a Pie Chart?
Use It When You Want To... Why
Show part-to-whole relationships Each slice adds up to 100%
Visualize proportions or shares Who has the biggest slice?
Compare categories at a glance Easy to tell what dominates
Use it for simple, small datasets — not too many categories!
Real-Life Scenario:
Let’s say you conducted a poll in your class of 100 students asking:
“Which tool are you learning right now?”
You got this result:
Tool No. of Students
Python 40
SQL 30
Excel 20
Power BI 10
Code:
import [Link] as plt
languages = ['Python', 'SQL', 'Excel', 'Power BI']
students = [40, 30, 20, 10]
colors = ['skyblue', 'lightgreen', 'orange', 'pink']
[Link](figsize=(8, 6))
[Link](students,
labels=languages,
colors=colors,
autopct='%1.1f%%',
startangle=90,
explode=[0.1, 0, 0, 0],
shadow=True)
[Link]("Students Learning Different Data Tools")
plt.tight_layout()
[Link]()
Parameters Explained:
Param What It Does
labels Names on each slice
colors Set custom colors
autopct='%1.1f%%' Show percentage on each slice
startangle=90 Rotate the chart for cleaner view
explode=[...] Pull out one slice for highlight
shadow=True Adds a 3D effect
tight_layout() Adjust spacing automatically
HISTOGRAM – How Data is Spread Like Butter on Bread
What is a Histogram?
Let’s say you took 50 students’ Python test scores, and you want to understand:
“How many students scored between 0–20?
How many between 20–40? 40–60? etc.”
You don’t want to see each student’s score (like in a bar chart)…
You want to group them into ranges and see how frequent those ranges are.
🎯 That’s what a Histogram does:
● It groups numerical data into bins (ranges).
● Then it shows how many values fall into each bin.
● X-axis = range of values (bins)
● Y-axis = count (frequency)
It’s like saying:
"Give me the count of students who fall in each score range."
When to Use Histogram?
Use It To... Why It's Useful
Understand distribution Is your data skewed or balanced?
Find outliers or patterns Are most students failing or passing?
Explore numeric data like scores Bins show ranges
Spot if your data is normal or not Check for bell-curve, flatness, etc.
Real Scenario
You're analyzing Python test scores of students:
scores = [55, 65, 45, 70, 82, 85, 90, 33, 38, 48, 55, 59, 62, 67, 73, 75, 77, 79, 80, 81]
You want to group them like:
● 30–40
● 40–50
● 50–60
● 60–70
● etc.
Code:
import [Link] as plt
scores = [55, 65, 45, 70, 82, 85, 90, 33, 38, 48, 55, 59, 62, 67, 73, 75, 77, 79, 80, 81]
[Link](figsize=(8, 5))
[Link](scores, bins=[30, 40, 50, 60, 70, 80, 90, 100], color='skyblue', edgecolor='black')
[Link]("Distribution of Python Test Scores")
[Link]("Score Range")
[Link]("Number of Students")
[Link](axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
[Link]()
Parameters Explained:
Param What It Does
hist(data) Plots histogram
bins Sets the score ranges
color Fills the bars
edgecolor Outline of each bar
grid(axis='y') Grid only on y-axis (frequency)
tight_layout() Auto spacing
BOX PLOT – The Data Detective’s Tool
What is a Box Plot?
A box plot is a statistical graph that tells you:
● What’s normal
● What’s high
● What’s low
● And what’s weird (outliers!)
It gives you 5-number summary of your data:
1. Minimum
2. First Quartile (Q1)
3. Median (Q2)
4. Third Quartile (Q3)
5. Maximum
And also shows outliers, those points that are far away from the normal range.
🤔 Real-Life Analogy:
Imagine exam marks of students packed in a box:
● Middle value (median) is the thick line inside the box
● The box edges are Q1 and Q3
● Whiskers (lines outside box) are min and max
● Dots outside? Suspicious students 🤨 (Outliers)
Scenario:
Let’s say you collected Python exam scores from a batch of 20 students.
You want to know:
● What is the median score?
● Are there any outliers?
● Is the data skewed?
A box plot tells you everything in one graph.
Code:
import [Link] as plt
scores = [55, 65, 45, 70, 82, 85, 90, 33, 38, 48, 55, 59, 62, 67, 73, 75, 77, 79, 80, 81]
[Link](figsize=(6, 5))
[Link](scores, patch_artist=True, boxprops=dict(facecolor='lightblue',
color='black'),
medianprops=dict(color='red'), whiskerprops=dict(color='black'),
capprops=dict(color='black'), flierprops=dict(marker='o',
markerfacecolor='orange'))
[Link]("Box Plot of Python Scores")
[Link]("Scores")
[Link](axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
[Link]()
PARAMS EXPLAINED:
Param Use
boxplot(data) Draws the box plot
patch_artist=True Allows box color filling
boxprops, medianprops Style settings
flierprops Outlier styling
grid(axis='y') Horizontal grid for reference
Multiple Box Plots –
Scenario:
You’ve got test scores from two different classes:
● One for Python students
● One for SQL students
Now you want to compare their score distributions side by side using box plots.
Code:
import [Link] as plt
# Sample data
python_scores = [55, 65, 45, 70, 82, 85, 90, 33, 38, 48, 55, 59, 62, 67, 73, 75, 77, 79, 80,
81]
sql_scores = [42, 53, 47, 60, 61, 68, 70, 35, 40, 45, 58, 59, 60, 64, 66, 69, 71, 74, 76, 79]
# Combine into a list
data = [python_scores, sql_scores]
# Plotting
[Link](figsize=(8, 5))
[Link](data,
patch_artist=True,
labels=['Python', 'SQL'],
boxprops=dict(facecolor='lightblue', color='black'),
medianprops=dict(color='red'),
whiskerprops=dict(color='black'),
capprops=dict(color='black'),
flierprops=dict(marker='o', markerfacecolor='orange'))
[Link]("Box Plot Comparison – Python vs SQL Scores")
[Link]("Scores")
[Link](30,90)
[Link](range(30,91,5)
[Link](axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
[Link]()
Parameters in Action:
Part Use
data = [list1, list2] Plot multiple datasets
labels X-axis group names
boxprops, medianprops Styling
flierprops Style for outliers
patch_artist=True Allows color inside boxes