Data Analysis Using Python
Data Analysis Using Python
Instructions:
• Kindly go through the lectures/videos on our website [Link]
M
• Read this study material carefully and make your own handwritten short notes. (Short notes must not be
O
more than 5-6 pages)
.C
• Attempt the mock tests available on portal. LE
• Revise this material at least 5 times and once you have prepared your short notes, then revise your short
RA
3 Lists 6
3.1 Python List Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4 Dictionaries 8
4.1 Python Dictionary Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
5 Tuples 10
5.1 Creating tuples and basic operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.2 Python Tuple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
6 Sets 11
6.1 Python Set Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7 Control Flow 12
7.1 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7.2 Looping Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
M
O
8 3.1 Loop Control Statements 15
.C
9 Functions Commonly Used with for Loops in Python LE 17
12 Data Reshaping 29
HW
14 Slicing in Python 35
S
YU
15 Functions in Python 36
15.1 Recursion in Python Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
PI
20 Matplotlib Functions 55
2
M
O
.C
LE
LinkedIn
RA
AI
Youtube Channel
HW
Instagram
S
YU
Telegram Group
PI
1 Variables in Python
A variable is a name that refers to a value stored in memory. In Python, variables are created when you assign a
value to them.
Examples
M
x = 10
O
name = "Alice"
.C
pi_value = 3.14159
_is_valid = True
LE
RA
Numeric Types
• int: Integer numbers
S
# Examples
a = 5 # int
b = 3.14 # float
c = 2 + 3j # complex
String (str)
A string is a sequence of characters enclosed in single, double, or triple quotes.
s1 = ’Hello’
s2 = "World"
s3 = ’’’Python allows
multiline strings’’’
Boolean (bool)
Represents truth values: True or False.
is_python_easy = True
is_java_easy = False
Checking Data Types
You can use the type() function to check the type of a variable.
x = 10
print(type(x)) # <class ’int’>
s = "Hello"
print(type(s)) # <class ’str’>
Type Casting
Python allows conversion between data types.
x = 5
y = float(x) # int to float
z = str(x) # int to string
a = int("10") # string to int
M
O
.C
LE
RA
AI
S HW
YU
PI
3 Lists
A list is an ordered, mutable collection of elements. Lists allow duplicates and can hold heterogeneous types.
Creating lists
# empty list
lst1 = []
# list from literals
lst2 = [1, 2, 3]
# heterogeneous list
lst3 = [1, ’two’, 3.0, [4,5]]
# list from iterable
lst4 = list(range(5)) # [0,1,2,3,4]
# list comprehension
squares = [x*x for x in range(6)] # [0,1,4,9,16,25]
M
print(a[2]) # ’c’
O
print(a[-1]) # ’d’
.C
print(a[-2]) # ’c’
letters = [’a’,’b’,’c’,’d’,’e’,’f’]
LE
print(letters[1:4]) # [’b’,’c’,’d’]
RA
print(letters[:3]) # [’a’,’b’,’c’]
print(letters[3:]) # [’d’,’e’,’f’]
AI
print(letters[-3:]) # [’d’,’e’,’f’]
print(letters[::2]) # [’a’,’c’,’e’]
HW
Note: Slicing returns a new list — it is a shallow copy. If elements inside the list are mutable, they are shared
between the original and the slice.
PI
# membership
print(3 in [1,2,3]) # True
# iteration
for i, v in enumerate([’x’,’y’]):
print(i, v)
# unpacking
a, b, c = [1,2,3]
print(a, b, c)
3.1 Python List Functions
Function Description Example
append(x) Adds element x at the end. a=[1,2]; [Link](3) ⇒ [1,2,3]
extend(iterable) Adds all elements of iterable to a=[1,2]; [Link]([3,4]) ⇒
list. [1,2,3,4]
insert(i,x) Inserts x at index i. a=[1,3]; [Link](1,2) ⇒ [1,2,3]
remove(x) Removes first occurrence of x. a=[1,2,2,3]; [Link](2) ⇒
[1,2,3]
pop() Removes and returns last ele- a=[1,2,3]; [Link]() ⇒ 3
ment.
pop(i) Removes and returns element at a=[10,20,30]; [Link](1) ⇒ 20
index i.
clear() Removes all elements. a=[1,2]; [Link]() ⇒ []
index(x) Returns index of first occurrence a=[10,20,30]; [Link](20) ⇒ 1
of x.
count(x) Counts occurrences of x. a=[1,2,2,3]; [Link](2) ⇒ 2
sort() Sorts list in ascending order. a=[3,1,2]; [Link]() ⇒ [1,2,3]
sort(reverse=True) Sorts list in descending order. a=[1,3,2]; [Link](reverse=True)
⇒ [3,2,1]
M
reverse() Reverses the list in-place. a=[1,2,3]; [Link]() ⇒ [3,2,1]
copy() Returns a shallow copy. a=[1,2]; b=[Link]() ⇒ [1,2]
O
len(list) Returns number of elements. len([1,2,3]) ⇒ 3
.C
max(list) Returns maximum element. max([1,9,3]) ⇒ 9
min(list) Returns minimum element. LE min([4,2,7]) ⇒ 2
sum(list) Returns sum of elements. sum([1,2,3]) ⇒ 6
any(list) True if any element is True. any([0,0,1]) ⇒ True
RA
Creating dictionaries
# literals
d1 = {’a’: 1, ’b’: 2}
# empty dict
d2 = {}
# from pairs
d3 = dict([(’x’, 9), (’y’, 10)])
# from keyword args
d4 = dict(x=1, y=2)
# dict from keys with same default
keys = [’a’,’b’,’c’]
d = [Link](keys, 0) # {’a’:0,’b’:0,’c’:0}
M
print(d1[’a’]) # 1 -- raises KeyError if ’a’ missing
O
# safer alternatives
.C
print([Link](’z’)) # None
print([Link](’z’, ’def’)) # ’def’ LE
# nested safe access
data = {’user’: {’name’: ’Priya’, ’age’: 30}}
RA
Merging dictionaries
HW
c = a | b # {’x’:1,’y’:2}
YU
M
value pairs from another dictio-
nary.
O
setdefault(key) Returns value if key exists; else d={"a":1}; [Link]("b") ⇒
.C
inserts and returns None. None
setdefault(key, If key not found, inserts key with
LE [Link]("c",100) ⇒ 100
default) default value.
copy() Returns a shallow copy of dictio- d={"a":1}; x=[Link]()
RA
nary.
len(dict) Returns number of key-value len({"a":1,"b":2}) ⇒ 2
AI
pairs.
in Checks if key exists in dictionary. "a" in {"a":1,"b":2} ⇒ True
HW
fromkeys(iterable, [Link](["x","y"],0)
value) all keys. {”x”:0,”y”:0}
PI
5 Tuples
A tuple is an immutable, ordered sequence of values. Use tuples for fixed collections and for keys in dictionaries
when appropriate.
M
5.2 Python Tuple Functions
O
.C
Function Description Example
count(x) Returns number of times x ap- LE t=(1,2,2,3); [Link](2) ⇒ 2
pears in the tuple.
index(x) Returns index of first occurrence t=(10,20,30); [Link](20) ⇒ 1
RA
of x.
len(tuple) Returns number of elements. len((1,2,3)) ⇒ 3
AI
tuple(iterable)
in Checks if an item exists in the 2 in (1,2,3) ⇒ True
tuple.
PI
Creating sets
s1 = {1,2,3}
s2 = set([1,2,2,3]) # duplicates removed -> {1,2,3}
s3 = set() # empty set (note: {} creates empty dict)
s4 = frozenset([1,2]) # immutable set
M
# set algebra methods
O
A = {1,2,3}
.C
B = {3,4}
print([Link](B)) # {1,2,3,4} LE
print([Link](B)) # {3}
print([Link](B)) # {1,2}
RA
print([Link]({1,2,3,4})) # True
AI
S HW
YU
PI
6.1 Python Set Functions
Function Description Example
add(x) Adds element x to the set. s={1,2}; [Link](3) ⇒ {1,2,3}
update(iterable) Adds all elements from iterable s={1}; [Link]([2,3]) ⇒ {1,2,3}
to set.
remove(x) Removes element x; error if not s={1,2}; [Link](2) ⇒ {1}
found.
discard(x) Removes element x; no error if s={1,2}; [Link](5)
not found.
pop() Removes and returns a random s={10,20,30}; [Link]()
element (since set is unordered).
clear() Removes all elements. [Link]() ⇒ {}
copy() Returns a shallow copy. s={1,2}; t=[Link]()
union(t) Returns new set with elements {1,2}.union({2,3}) ⇒ {1,2,3}
from both sets.
intersection(t) Returns common elements of {1,2,3}.intersection({2,3,4}) ⇒
sets. {2,3}
difference(t) Returns elements present in set {1,2,3}.difference({3,4}) ⇒ {1,2}
but not in t.
M
sym diff(t) Returns symmetric difference. {1,2,3} ^ {3,4} ⇒ {1,2,4}
intersection update(t) Updates current set to intersec- s={1,2,3};
O
tion with t. [Link] update({2,3})
.C
⇒ {2,3}
difference update(t) Removes elements found in t
LE s={1,2,3};
from the set. [Link] update({3}) ⇒ {1,2}
sym diff update(t) Updates set to symmetric differ- s={1,2};
RA
the set.
YU
7 Control Flow
Control Flow Statements in Python
Control flow statements determine the order in which instructions are executed in a program. They allow decision-
making, looping, branching, and repeating actions based on conditions.
Python provides three major categories:
• Conditional statements (if, elif, else)
• Looping statements (for, while)
if-else Statement
If the condition is false, the else block executes.
x = 3
if x % 2 == 0:
print("Even")
M
else:
print("Odd")
O
Output:
.C
Odd LE
if-elif-else
RA
marks = 85
HW
print("Grade B")
elif marks >= 60:
print("Grade C")
PI
else:
print("Grade D")
Output:
Grade B
Nested if
if statements inside another if block.
x = 10
if x > 0:
print("Positive")
if x % 2 == 0:
print("Even Number")
Output:
Positive
Even Number
7.2 Looping Statements
Loops are used to execute statements repeatedly.
Python supports:
• for loop
• while loop
1. for Loop
Used to iterate over sequences (list, tuple, string, range).
Syntax:
Example:
M
Output:
O
.C
1
2 LE
3
4
RA
5
AI
if i == 5:
break
print(i)
Output stops at 4.
Output skips 3.
2. while Loop
Executes as long as the condition is true.
Syntax:
while condition:
statements
Example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
M
Infinite Loop Example
O
while True:
.C
print("Press Ctrl+C to stop")
LE
8 3.1 Loop Control Statements
RA
1 break Statement
HW
if i == 4:
YU
break
print(i)
PI
Output:
0
1
2
3
for i in range(5):
pass
for i in range(3):
print(i)
else:
print("Loop Completed")
Output:
0
1
2
OM
Loop Completed
.C
Example with break: LE
for i in range(3):
if i == 1:
RA
break
print(i)
I
else:
WA
print("Completed")
SH
Output:
YU
0
PI
5. Nested Loops
Loops inside another loop.
Output:
1 1
1 2
2 1
2 2
3 1
3 2
6. Match-Case (Python 3.10+)
Similar to switch-case in other languages.
choice = 2
match choice:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Default Case")
Output:
Two
OM
1. range() Function
.C
LE
range() generates a sequence of numbers and is the most commonly used function in for loops.
RA
Syntax:
I
Examples:
SH
for i in range(5):
YU
print(i)
PI
Output:
0
1
2
3
4
Using start and step:
Output:
0 apple
1 banana
2 mango
Useful when you need both index and value.
3. zip() Function
zip() combines multiple sequences and iterates over them simultaneously.
M
names = ["Amit", "Riya", "Sam"]
O
scores = [85, 90, 78]
.C
for n, s in zip(names, scores): LE
print(n, s)
RA
Output:
Amit 85
AI
Riya 90
Sam 78
HW
4. sorted() Function
S
YU
numbers = [5, 3, 9, 1]
for n in sorted(numbers):
print(n)
Output:
1
3
5
9
Sorting in reverse:
for n in sorted(numbers, reverse=True):
print(n)
5. reversed() Function
reversed() iterates over the sequence in reverse order.
for n in reversed(items):
print(n)
Output:
30
20
10
6. len() Function
len() returns the length of a sequence. often used with range()
for i in range(len(names)):
OM
print(i, names[i])
for ch in "DATA":
I
WA
print(ch)
SH
Output:
D
YU
A
PI
T
A
d = {"A":10, "B":20}
for k in d:
print(k)
Values:
for v in [Link]():
print(v)
Key-value pairs:
for k, v in [Link]():
print(k, v)
9. Iteration over Sets
Sets produce unique, unordered values.
s = {1, 2, 3}
for x in s:
print(x)
Output:
[0, 1, 4, 9, 16]
M
O
.C
LE
RA
AI
S HW
YU
PI
10 Error Handling in Python
Error handling allows a program to respond gracefully when something goes wrong. Instead of terminating abruptly,
Python provides mechanisms to catch and manage errors using exception handling.
The main construct is the try-except block.
1. try-except Block
Basic structure:
try:
code that may cause an error
except:
code that runs if an error occurs
Example:
try:
x = 10 / 0
except:
print("An error occurred")
OM
Output:
An error occurred
.C
LE
2. Catching Specific Exceptions
RA
try:
SH
num = int("abc")
except ValueError:
YU
Output:
• TypeError
• FileNotFoundError
• IndexError
• KeyError
3. Multiple except Blocks
Different errors can be handled separately.
try:
a = [1, 2, 3]
print(a[5])
except IndexError:
print("Index out of range")
except Exception:
print("General error")
4. else Block
The else block executes only if no exception occurs.
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful:", x)
OM
Output:
5. finally Block
I
The finally block always executes, whether or not an exception occurs. Often used for cleanup (closing files, releasing
WA
resources).
SH
try:
YU
f = open("[Link]", "r")
print([Link]())
PI
except FileNotFoundError:
print("File not found")
finally:
print("Execution Completed")
Output:
age = -4
if age < 0:
raise ValueError("Age cannot be negative")
Output:
class AgeError(Exception):
pass
M
O
age = -1
.C
try: LE
if age < 0:
raise AgeError("Age cannot be negative")
RA
except AgeError as e:
print(e)
AI
Output:
HW
1. Definition
A DataFrame is:
• Two-dimensional (rows × columns)
• Labeled (column names + row index)
• Heterogeneous (each column may have different data types)
• Mutable (data can be added, removed, modified)
2. Creating a DataFrame
(a) From a Python Dictionary
import pandas as pd
data = {"Name":["Amit","Riya","Piyush"], "Marks":[85,92,78], "City":["Mumbai","Delhi","Pune"]}
M
df = [Link](data)
O
(b) From a List of Lists
.C
df = [Link]([[1,"Amit"], [2,"Riya"]], columns=["Roll","Name"])
(c) From a CSV File LE
df = [Link] csv("[Link]")
(d) From an SQL Query
RA
3. DataFrame Components
HW
A DataFrame contains:
• Index: Row labels (default: 0,1,2,. . . )
• Columns: Names of attributes
S
YU
4. Accessing Data
(a) Select a single column
df["Name"]
(b) Select multiple columns
df[["Name","City"]]
(c) Select row by label (loc)
[Link][1]
(d) Select row by position (iloc)
[Link][2]
(e) Select a specific cell
[Link][0,"Marks"]
[Link][1,2]
5. Filtering Data
(a) Conditional filtering
df[df["Marks"] > 80]
(b) Multiple conditions
df[(df["Marks"] > 80) & (df["City"] == "Mumbai")]
6. Adding New Columns
df["Status"] = ["Pass","Pass","Fail"]
Using a function:
df["Marks2"] = df["Marks"].apply(lambda x: x+5)
7. Removing Data
Drop a column:
[Link]("City", axis=1)
Drop multiple columns:
[Link](["Marks","City"], axis=1)
Drop a row:
[Link](1)
8. Descriptive Statistics
[Link]()
df["Marks"].mean()
df["Marks"].median()
df["Marks"].max()
M
df["Marks"].min()
df["Marks"].std()
O
.C
9. Handling Missing Values LE
Check missing values:
[Link]().sum()
RA
Sort by a column:
YU
[Link] values("Marks")
Sort descending:
PI
13. Concatenation
Row-wise:
[Link]([df1, df2], axis=0)
Column-wise:
[Link]([df1, df2], axis=1)
14. Exporting Data
To CSV:
[Link] csv("[Link]")
To Excel:
[Link] excel("[Link]")
To SQL Table:
[Link] sql("students", connection)
M
dtypes Returns data type of each col- [Link]
O
umn.
rename() Renames columns. [Link](columns={"Name":"FullName"})
.C
drop() Drops rows or columns. LE [Link]("City", axis=1)
sort values() Sorts by column values. [Link] values("Marks")
sort index() Sorts DataFrame by index. [Link] index()
RA
patterns.
assign() Adds new columns. [Link](Age2=df["Age"]+1)
apply() Applies a function to columns or df["Marks"].apply(lambda x: x+5)
S
rows.
YU
M
O
.C
LE
RA
AI
S HW
YU
PI
R DataFrame Functions with Examples
Function Description Example
[Link]() Creates a new DataFrame. df <- [Link](Name, Marks,
City)
head(df) Displays first 6 rows. head(df)
tail(df) Displays last 6 rows. tail(df)
str(df) Shows structure, types, and pre- str(df)
view.
summary(df) Summary statistics of columns. summary(df)
names(df) Returns column names. names(df)
rownames(df) Returns row names. rownames(df)
nrow(df) Number of rows. nrow(df)
ncol(df) Number of columns. ncol(df)
dim(df) Returns (rows, columns). dim(df)
df$Column Accesses a column. df$Marks
df[, "col"] Column selection using name. df[, "City"]
df[i, ] Access row i. df[2, ]
df[i, j] Access cell at row i, column j. df[1, 2]
subset() Filter rows / select columns. subset(df, Marks > 80)
M
order() Sort DataFrame. df[order(df$Marks), ]
O
rbind() Combine row-wise. rbind(df1, df2)
.C
cbind() Combine column-wise. cbind(df1, df2)
merge() SQL-style join. LE merge(df1, df2, by="ID")
unique(df) Returns unique rows. unique(df)
duplicated(df) Checks for duplicate rows. duplicated(df)
RA
Marks+5})
apply() Apply function on rows/- apply(df[,2:3], 2, mean)
columns.
PI
Below are detailed reshaping concepts in Python (Pandas) and R, with examples and outputs.
M
Amit 80 90
O
Riya 85 88
.C
a) melt(): Wide to Long LE
Code:
RA
Amit Math 80
HW
Amit Science 90
Riya Math 85
Riya Science 88
S
YU
M
Output:
Rows of df1 and df2 are appended.
O
.C
g) merge(): SQL Style Join
Code:
LE
[Link](df1, df2, on="ID")
RA
Output:
ID Name Score
1 Amit 80
AI
2 Riya 90
S HW
YU
PI
2. Data Reshaping in R
Example Dataset
Name Math Science
Amit 80 90
Riya 85 88
M
b) dcast(): Long to Wide
O
Code:
.C
df wide <- dcast(df long, Name ~ Subject, [Link]="Score")
Output: LE
Name Math Science
Amit 80 90
RA
Riya 85 88
AI
Code:
library(tidyr)
df long <- df %>% pivot longer(cols=Math:Science, names to="Subject", values to="Score")
S
Output:
YU
(Same as melt)
PI
M
O
.C
LE
RA
AI
HW
S
YU
PI
13 Regular Expressions (Regex) and Slicing in Python
1. Regular Expressions (Regex)
Regular Expressions (Regex) are patterns used to search, match, and manipulate text. Python provides the re
module for regex operations.
M
O
Common Regex Patterns
.C
LE
RA
AI
S HW
YU
PI
Regex Example with Output
Code:
import re
text = "Contact: 9876543210"
[Link]("\d10", text)
Output:
["9876543210"]
M
O
.C
LE
RA
AI
S HW
YU
PI
14 Slicing in Python
Slicing is used to extract a portion of a sequence (string, list, tuple) using the format:
Rules
• start = index to begin slice (inclusive)
M
s[-3:] ”HON”
O
s[::2] ”PTO”
s[::-1] ”NOHTYP” (reverse string)
.C
List Slicing Example
LE
RA
Code Output
lst = [10,20,30,40,50] –
lst[1:4] [20,30,40]
AI
lst[::-1] [50,40,30,20,10]
HW
lst[::2] [10,30,50]
Advanced Slicing
S
YU
Function Syntax
def function name(parameters):
statements
return value
M
Code:
O
def greet(name="Guest"):
.C
return "Hello, " + name
greet() LE
Output:
"Hello, Guest"
RA
Code:
HW
def total(*nums):
return sum(nums)
total(1,2,3,4)
S
Output:
YU
10
PI
print(factorial(5))
Output:
120
M
Explanation
O
5! = 5 × 4 × 3 × 2 × 1
.C
Base case: when n == 0, return 1.
LE
Example 2: Fibonacci Using Recursion
RA
Code:
AI
def fib(n):
if n <= 1:
HW
return n
return fib(n-1) + fib(n-2)
S
print(fib(6))
YU
Output:
8
PI
Explanation
Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, . . .
print(sum digits(1234))
Output:
10
1 + 2 + 3 + 4 = 10
Example 4: Reverse a String Recursively
Code:
def reverse(s):
if len(s) == 0:
return s
return reverse(s[1:]) + s[0]
print(reverse("PYTHON"))
Output:
"NOHTYP"
M
O
.C
LE
RA
AI
S HW
YU
PI
16 File Management in Python
File management refers to reading from and writing to files stored on disk. Python provides built-in functions for
handling files using the open() function.
1. Opening a File
The syntax for opening a file is:
file = open("filename", "mode")
File Modes
Mode Description
"r" Read mode (file must exist)
"w" Write mode (overwrites file or creates new one)
"a" Append mode (adds data to end of file)
"x" Creates new file, error if file exists
"b" Binary mode (images, videos, pdf)
"t" Text mode (default)
"r+" Read + Write
M
"w+" Write + Read
O
.C
2. Reading Files LE
a) read() – Reads entire file
RA
Code:
file = open("[Link]", "r")
AI
content = [Link]()
HW
print(content)
[Link]()
Output (example):
S
Hello World!
YU
Welcome to Python.
PI
M
O
4. Using with Statement (Recommended)
.C
The with keyword automatically closes the file.
LE
Code:
RA
Advantages
• No need to call close()
S
YU
7. Deleting Files
Code:
import os
[Link]("[Link]")
Output:
M
(File deleted successfully)
O
.C
8. Handling Exceptions in File Operations LE
Code:
RA
try:
file = open("[Link]", "r")
AI
print([Link]())
except FileNotFoundError:
HW
Output:
S
M
O
.C
Figure 1: Source:[Link]
LE
RA
AI
S HW
YU
PI
Figure 2: Source:[Link]
These are classic visualizations suitable for most use cases and provide quick insights.
1. Bar Chart
A bar chart uses rectangular bars whose lengths represent values. Bars may be vertical or horizontal.
When to use: Comparing values across categories. Useful for distributions of categorical data.
Best practices:
M
O
.C
LE
RA
Figure 3: Histogram
AI
A histogram visualizes the distribution of a continuous variable by grouping values into bins.
HW
3. Column Chart
A column chart is a vertical bar chart used to compare category values.
When to use: Comparing categories, ranking values.
Best practices:
• Avoid distracting 3D effects.
• Highlight key columns with contrasting colors.
M
O
Figure 4: Column Chart
.C
4. Line Chart
LE
A line chart connects data points with straight lines to show changes over an ordered axis.
When to use: Visualizing trends over time (growth, cycles).
RA
Best practices:
AI
S HW
YU
PI
M
6. KPI Chart
O
A minimal visual showing key performance metrics, often with a small trend indicator.
.C
When to use: Quick decision-making for metrics such as revenue, churn, or NPS.
Best practices: LE
RA
AI
S HW
YU
PI
M
O
Charts for Comparing Values
.C
8. Treemap
LE
A hierarchical chart using nested rectangles sized by value.
RA
9. Pareto Chart
YU
M
O
.C
LE
RA
AI
HW
M
• Limit series to avoid clutter.
O
.C
18. Step Chart
A line chart variant showing discrete changes with horizontal and vertical segments.
LE
When to use: Displaying values that change at specific intervals.
Best practices:
RA
Financial chart showing open, high, low, close for each period.
When to use: Analyzing price movements of stocks or currencies.
Best practices:
PI
M
Plots points on geographic coordinates.
When to use: Visualizing location-based events (stores, deliveries).
O
Best practices:
.C
• Use clustering in dense locations. LE
• Use color or size to encode value.
RA
Best practices:
HW
24. Heatmap
Grid or map where color intensity encodes values.
When to use: Identifying patterns across matrices or geographic regions.
PI
Best practices:
• Use intuitive color scales.
• Avoid overcrowding.
.C
• Label axes, legends, and annotations clearly.
LE
• Avoid unnecessary visual decorations or 3D effects.
RA
M
O
.C
1.2 Bar Chart
Code:
LE
cities = ["Mumbai","Delhi","Pune"]
RA
values = [25,30,18]
[Link](cities, values)
[Link]("City Counts")
AI
[Link]()
Output: Vertical bars for Mumbai(25), Delhi(30), Pune(18).
S HW
Code:
sizes = [40,30,20,10]
PI
labels = ["A","B","C","D"]
[Link](sizes, labels=labels, autopct="%1.1f%")
[Link]()
Output: A circular pie chart with percentage labels.
1.4 Histogram
Purpose: Visualize distribution of data.
Code:
data = [10,20,20,30,40,40,40,50]
[Link](data, bins=5)
[Link]("Value")
[Link]("Frequency")
[Link]()
Output: Bars showing frequency distribution of the data.
1.5 Scatter Plot
Code:
x = [1,2,3,4,5]
y = [5,4,6,5,7]
[Link](x,y)
[Link]("X")
[Link]("Y")
[Link]()
Output: Dots plotted showing correlation between X and Y.
M
O
.C
LE
RA
AI
S HW
YU
PI
19 Charts and Graphs in R
R provides powerful visualization through Base Plotting and ggplot2.
M
O
2.3 Pie Chart (Base R)
.C
Code: LE
sizes <- c(40,30,20,10)
labels <- c("A","B","C","D")
RA
pie(sizes, labels)
Output: A pie chart with 4 slices labeled A, B, C, D.
AI
HW
Line Plot
PI
Code:
df <- [Link](x=c(1,2,3,4), y=c(10,20,15,25))
ggplot(df, aes(x,y)) + geom line(color="blue")
Output: A smooth blue line chart.
Bar Plot
Code:
df <- [Link](city=c("Mumbai","Delhi","Pune"), val=c(25,30,18))
ggplot(df, aes(city, val)) + geom bar(stat="identity", fill="orange")
Output: Orange bars for the values.
Histogram
Code:
ggplot(df, aes(values)) + geom histogram(bins=5, fill="purple")
Scatter Plot
Code:
df <- [Link](x=c(1,2,3,4), y=c(5,4,6,5))
ggplot(df, aes(x,y)) + geom point(color="red")
Output: Red dots showing the scatter pattern.
Summary of Charts
Chart Use Case Python / R Function
Line Chart Trends over time plot(), geom line()
Bar Chart Category comparison bar(), geom bar()
Pie Chart Part-to-whole pie(), [Link]()
Histogram Distribution hist(), geom histogram()
Scatter Plot Correlation scatter(), geom point()
M
O
.C
LE
RA
AI
S HW
YU
PI
20 Matplotlib Functions
Function Description
1. Basic Plotting
plot() Draws line plot.
scatter() Creates scatter plot.
bar() Vertical bar chart.
barh() Horizontal bar chart.
pie() Pie chart.
hist() Histogram.
boxplot() Box-and-whisker plot.
stem() Stem plot.
stackplot() Stacked area plot.
fill between() Fill region between curves.
2. Labels, Titles, Legends
title() Set plot title.
xlabel() Set x-axis label.
ylabel() Set y-axis label.
legend() Show legend.
text() Add text inside plot.
M
annotate() Add annotations.
Toggle grid lines.
O
grid()
3. Figure and Subplots
.C
figure() Create a figure object.
LE
subplot() Create subplots in a grid.
subplots() Create figure + axes.
RA
Function Description
HW
M
jointplot() Joint distribution + marginal distributions.
O
pairplot() Pairwise relationships between all numerical variables.
.C
3. Relational Plots
relplot() High-level interface for relational plots (scatter, line).
LE
scatterplot() Scatter plot of numeric variables.
lineplot() Line plot with aggregation over observations.
RA
clustermap()
YU
6. Multi-Plot Grids
FacetGrid() Multi-plot grid for categorical values.
PairGrid() Grids of pairwise plots for variables.
PI
M
subplots(), figure(), JointGrid.
O
add subplot().
Better for detailed, production- Better for exploratory data analysis (EDA).
.C
ready customization. LE
Performance is very fast because Slightly slower but provides better statistical visualizations.
it’s low-level.
RA
Output:
array([1, 2, 3, 4])
OM
Function Description
[Link]((m,n)) Matrix filled with 0s.
.C
LE
[Link]((m,n)) Matrix filled with 1s.
[Link]((m,n), value) Matrix filled with a constant.
RA
2. Array Attributes
PI
Attribute Description
[Link] Number of dimensions.
[Link] Tuple of array dimensions.
[Link] Total number of elements.
[Link] Data type of array elements.
[Link] Size of each element (bytes).
Example:
a = [Link]([[1,2,3],[4,5,6]])
[Link] ⇒ (2, 3)
4. Mathematical Operations
NumPy performs vectorized operations (fast and automatic).
Operation Example
Element-wise add a + b
Element-wise multiply a * b
Dot product [Link](a, b)
Power a ** 2
Log [Link](a)
Sine, Cosine [Link](a), [Link](a)
Example:
a = [Link]([1,2,3])
a * 2 ⇒ [2, 4, 6]
OM
.C
5. Aggregate Functions LE
a = [Link]([1,2,3,4])
Function Output
RA
[Link](a) 10
I
[Link](a) 1
WA
[Link](a) 4
[Link](a) 2.5
SH
[Link](a) 2.5
[Link](a) Standard deviation
YU
[Link](a) Variance
PI
6. Reshaping Arrays
6.1 Reshape
a = [Link](6)
[Link](2,3) ⇒ 2x3matrix
6.2 Flatten
[Link]() ⇒ 1Darray
6.3 Transpose
b.T ⇒ transposeof b
7. Stacking Arrays
Function Description
[Link]((a,b)) Horizontal stacking.
[Link]((a,b)) Vertical stacking.
[Link]((a,b), General concatenation.
axis=0)
8. Copies vs Views
• View shares data with original array.
• Copy creates new data.
Example:
a = [Link]([1,2,3])
b = [Link]()
c = [Link]()
Modifying b affects a, but modifying c does not.
OM
.C
Function Usage
[Link](m,n) Uniform distribution.
LE
[Link](m,n) Normal distribution.
[Link](a,b,n) Random integers.
RA
Example:
WA
[Link](1,10,5) ⇒ [3, 7, 2, 9, 1]
SH
Function Description
[Link]("[Link]", a) Save array in binary format.
[Link]("[Link]") Load array.
[Link]("[Link]", a) Save as text.
[Link]("[Link]") Load text file.
11. Broadcasting
Broadcasting allows operations between arrays of different shapes.
Example:
a = 1 2 3
b = 5
a + b ⇒ [6, 7, 8]
Rules: