0% found this document useful (0 votes)
4 views44 pages

Data Visualization With Python Lab Manual

The document is a laboratory manual for a Data Visualization with Python course at Don Bosco Institute of Technology, detailing course objectives, program outcomes, and various Python programming assignments. It includes practical exercises on data visualization techniques using libraries like Matplotlib and Plotly, as well as assessment rubrics for evaluating student performance. The manual aims to equip students with essential skills in Information Science and Engineering through hands-on programming experience.
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)
4 views44 pages

Data Visualization With Python Lab Manual

The document is a laboratory manual for a Data Visualization with Python course at Don Bosco Institute of Technology, detailing course objectives, program outcomes, and various Python programming assignments. It includes practical exercises on data visualization techniques using libraries like Matplotlib and Plotly, as well as assessment rubrics for evaluating student performance. The manual aims to equip students with essential skills in Information Science and Engineering through hands-on programming experience.
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

DON BOSCO INSTITUTE OF

TECHNOLOGY
(An Autonomous Institute, Affiliated to VTU, Belagavi) Mysuru
Road, Kumbalagodu, Bengaluru – 560 074.

Department of Information Science & Engineering


(UG Program Accredited by NBA 2025-2028)

Data Visualization with Python


LABORATORY MANUAL

III Semester Course


Code: B24ISL374

w.e.f September 2025


Document Log

Name of the document Data Structures Laboratory Manual

Subject code B24ISL38

Scheme 2024

Current version number and date V 1.0 / 05.08.2025

[Link] G M
Manual Prepared by [Link] A B

Dr. B K Raghavendra
Approved by
HOD - Dept. of ISE, DBIT
Table of Contents

Sl. No. Particulars Page #


1 Vision and Mission of Department i

2 PEOs and PSOs i

3 POs ii

4 Course details iii


 Course Outcomes
 CO-PO-PSO Mapping
5 RUBRICS for CIE and SEE iv
LAB PROGRAMS
a) Write a python program to find the best of two test
Program 1
average marks out of three test’s marks accepted
from the user.
b) Develop a Python program to check whether a given 1
number is palindrome or not and also count the number of
occurrences of each digit in the input number.

Program 2 a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a


Python program which accepts a value for N (where N 5
6 >0) as input and pass this value to the function.
Display suitable error message if the condition for
input value is not followed.
b) Develop a python program to convert binary to
decimal, octal to hexadecimal using functions
a) Write a Python program that accepts a sentence and find
Program 3 the number of words, digits, uppercase letters and lowercase
letters.
b) Write a Python program to find the string similarity
between two given strings
Sample Output: Original string:
8
Sample Output: Original string:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: Similarity
between two said strings:1.0 0.967741935483871
Program 4 a) Write a Python program to Demonstrate how to Draw
a Bar Plot using Matplotlib.
11
b) Write a Python program to Demonstrate how to Draw
a Scatter Plot using Matplotlib.
Program 5 a) Write a Python program to Demonstrate how to Draw a
Histogram Plot using Matplotlib. 15
b) Write a Python program to Demonstrate how to Draw a Pie
Chart using Matplotlib.
a) Write a Python program to illustrate Linear Plotting using
Program 6 Matplotlib. 18
b) Write a Python program to illustrate liner plotting with line
formatting using Matplotlib
Write a Python program which explains uses of customizing 21
Program 7 seaborn plots with Aesthetic functions.

Write a Python program to explain working with bokeh line


Program 8
graph using Annotations and Legends. 23

a) Write a Python program for plotting different types of plots


using Bokeh.
Write a Python program to draw 3D Plots using Plotly
Program 9
Libraries. 25
Program 10 a) Write a Python program to draw Time Series using
Plotly Libraries. 27

b) Write a Python program for creating Maps using Plotly


Libraries.
7 VIVA QUESTIONS 32
Vision of the Department

Empower the students to thrive for excellence in the area of Information Science and
Engineering to use technology for sustainable development for social needs.

Mission of the Department

M1: To provide theoretical and practical knowledge of Information Science and


Engineering.
M2: To provide inter disciplinary knowledge to be the leaders with social responsibility.
M3: To collaborate with industry to facilitate content beyond syllabus.
M4: To promote team work through projects, co-curricular and social activities.

Program Educational Objectives (PEOs)

PEO1: Graduates will contribute in development of software applications keeping


abreast of the development.
PEO2: Exhibit competence as individual, in teams with leadership and managerial skills.
PEO3: By optimizing the technology, the graduates will be able to adopt lifelong learning.

Program Specific Outcomes (PSOs)

PSO1: Apply the Mathematical tools, Electronics & Embedded Systems Knowledge,
and Programming Knowhow to develop software’s.
PSO2: Use of Artificial Intelligence and Machine Learning, High-Performance
Computing, Cloud Computing, Network Security technologies and Software
Engineering for providing solutions to the technological and social needs.
PSO3: Work individually and in teams, ethically exhibiting the managerial and
leadership skills with sustainable Environment.

[i]
Knowledge and Attitude Profile (WK)
WK1 A systematic, theory-based understanding of the natural sciences applicable to the
discipline and awareness of relevant social sciences.
WK2 Conceptually-based mathematics, numerical analysis, data analysis, statistics and
formal aspects of computer and information science to support detailed analysis
and modelling applicable to the discipline.
WK3 A systematic, theory-based formulation of engineering fundamentals required
in the engineering discipline.
WK4 Engineering specialist knowledge that provides theoretical frameworks and bodies
of knowledge for the accepted practice areas in the engineering discipline; much is
at the forefront of the discipline.
WK5 Knowledge, including efficient resource use, environmental impacts, whole-life
cost, re-use of resources, net zero carbon, and similar concepts, that supports
engineering design and operations in a practice area.
WK6 Knowledge of engineering practice (technology) in the practice areas in the
engineering discipline.
WK7 Knowledge of the role of engineering in society and identified issues in engineering
practice in the discipline, such as the professional responsibility of an engineer to
public safety and sustainable development
WK8 Engagement with selected knowledge in the current research literature of the
discipline, awareness of the power of critical thinking and creative approaches to
evaluate emerging issues.
WK9 Ethics, inclusive behavior and conduct. Knowledge of professional ethics,
responsibilities, and norms of engineering practice. Awareness of the need for
diversity by reason of ethnicity, gender, age, physical ability etc. with mutual
understanding and respect, and of inclusive attitudes.

[ii]
Program Outcomes
PO1 Engineering Knowledge: Apply knowledge of mathematics, natural science,
computing, engineering fundamentals and an engineering specialization as
specified in WK1 to WK4 respectively to develop to the solution of complex
engineering problems.
PO2 Problem Analysis: Identify, formulate, review research literature and analyze
complex engineering problems reaching substantiated conclusions with
consideration for sustainable development. (WK1 to WK4)
PO3 Design/development of Solutions: Design creative solutions for complex
engineering problems and design/develop systems/components/processes to
meet identified needs with consideration for the public health and safety, whole-
life cost, net zero carbon, culture, society and environment as required. (WK5)
PO4 Conduct Investigations of Complex Problems: Conduct investigations of complex
engineering problems using research-based knowledge including design of
experiments, modelling, analysis & interpretation of data to provide valid
conclusions. (WK8).
PO5 Engineering Tool Usage: Create, select and apply appropriate techniques,
resources and modern engineering & IT tools, including prediction and modelling
recognizing their limitations to solve complex engineering problems. (WK2 and
WK6)
PO6 The Engineer and The World: Analyze and evaluate societal and environmental
aspects while solving complex engineering problems for its impact on
sustainability with reference to economy, health, safety, legal framework, culture
and environment. (WK1, WK5, and WK7).
PO7 Ethics: Apply ethical principles and commit to professional ethics, human values,
diversity and inclusion; adhere to national & international laws. (WK9)
PO8 Individual and Collaborative Team work: Function effectively as an individual,
and as a member or leader in diverse/multi-disciplinary teams.
PO9 Communication: Communicate effectively and inclusively within the engineering
community and society at large, such as being able to comprehend and write
effective reports and design documentation, make effective presentations
considering cultural, language, and learning differences
PO10 Project Management and Finance: Apply knowledge and understanding of
engineering management principles and economic decision-making and apply
these to one’s own work, as a member and leader in a team, and to manage
projects and in multidisciplinary environments.
PO11 Life-long learning: Recognize the need for, and have the preparation and ability for
i) independent and life-long learning ii) adaptability to new and emerging
technologies and iii) critical thinking in the broadest context of technological
change. (WK8)

[iii]
Course Outcomes

At the end of the course, student will be able to

CO1 Explain the structure and functionality of operating system.


CO2 Apply appropriate CPU scheduling algorithms for the given problem.
CO3 Analyze the various techniques for process synchronization and deadlock
handling.
CO4 Apply the various techniques for memory management.
CO5 Explain file and secondary storage management strategies.

CO-PO-PSO Mapping

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PSO1 PSO2 PSO3
CO1 3 2 1 - 3 - - 1 - - 1 3 - 1
CO2 3 2 1 - 3 - - 1 - - 1 3 - 1
CO3 3 2 1 - 3 - - 1 - - 1 3 - 1
CO4 3 2 1 - 3 - - 1 - - 1 3 - 1
CO5 3 2 1 - 3 - - 1 - - 1 3 - 1
AVG 3 2 1 - 3 - - 1 - - 1 3 - 3

[iv]
RUBRICS FOR CIE & SEE

WEEKLY ASSESSMENT – 30 marks

Sl. No ACTIVITY MARKS


1 Record +Viva 30

LAB RUBRICS
Rubrics for Evaluation of Lab Record:

Ma Good Satisfactory Poor


Attribute
x 4-5 1-3 0
Mark
s
 Written complete  Written Program  Not submitted
program without any with few logical  Input and
errors errors. expected output
Write Up and is not written
 Written input and  Written input and
Time expected output for all expected output for
5
Manageme the test cases. few test cases.
nt  Written program  Written program
with proper with moderate
indentation indentation
 Index entry promptly
done and submits on
time
Max
Marks 15-20 5-14 0-4
Conduction  All possible cases of  The code is not  Unable to
of input and output tested with all execute within
20
experiment demonstrated possible cases. the
allotted
Max
Marks 4-5 1-3 0
 Able to explain the  Partially  Not
design of algorithm and understood the logic understood the
Viva 5 logic. of the experiment. logic of the
 Able to answer all  Able to answer 1 out experiment.
question related to the of 3 questions  Not answering
concept. any question

INTERNAL ASSESSMENT EVALUATION


(End of Semester)

Sl. No ACTIVITY MARKS


1 Write-up 15
2 Conduction 70

[v]
3 Viva 15
100
TOTAL (scaled down to 20)
MARKS

[vi]
Rubrics for Evaluation of Internal Test:

Max Excellent Good Satisfactory Poor


Attribute
Mark 11-15 6-10 1-5 0
s
 Completes  Completes  Incomplet  Change
source code. source code. e source of program
 No syntax and  Syntax and code.
Write-up logical errors logical errors  All
15
 All possible exist. possible
inputs listed with inputs listed
expected with
output expected
output
Max
Mark 60-70 20-59 11-19 0-10
s
 Able to debug  Able to  Able to  Not able to
the program and execute program clear the clear the
get the right set of for few possible errors. errors and
Execution 70
outputs inputs without  Not able execute the
 Able to modify the errors to execute program
Program as per program
the examiner’s
Direction
Max
Mark 11-15 6-10 1-5 0
s
 Able to answer  Able to answer 3  Able to  Not able to
Viva - 15 questions out of answer 2 - 5 answer
all questions
Voce 5 questions questions any
correctly
correctly questions.

FINAL INTERNAL ASSESSMENT CALCULATION


Sl . No ACTIVITY MARKS
1 Average of weekly entries 30
2 Internal Assessment 20
TOTAL 50

[vii
B24IS374 – Data Visualization with Python Laboratory Manual

Program 1a. Write a python program to find the best of two test average marks out of three
test, marks accepted from the user.
APPLICATIONS / IMPORTANCE: Application of this Program:

1. Education Systems – Many schools, colleges, and universities use “best of two” or

“best of three” policies to reduce the effect of one poor performance.

2. Fair Assessment – Ensures students are not penalized heavily for one bad test day,

and their consistent performance is rewarded.

3. Competitive Exams – Some exams consider the best scores for final ranking or

eligibility.

4. Data Analysis – Useful in performance evaluation systems where multiple test results

are recorded and the best ones are considered.

5. Practical Decision Making – Helps students and teachers understand performance

trends and strengths.

SOURCE CODE:

test1=float(input("Enter test1 marks:"))

test2=float(input("Enter test2 marks:"))

test3=float(input("Enter test3 marks:"))

if(test1<=test2 and test1<=test3):

min_score=test1 elif(test2<=test1 and test2<=test3):

min_score=test2 else:

min_score=test3

print("minimum score among the three test is:",min_score);

average=(test1+test2+test3-min_score)/2

print("Average of Best two test is:",average);

SAMPLE OUTPUT
INPUT
Enter test1 marks:99

Enter test2 marks:98

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 1


B24IS374 – Data Visualization with Python Laboratory Manual

Enter test3 marks:95

OUTPUT

minimum score among the three test

is:95.0 Average of Best two test is: 98

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 2


B24IS374 – Data Visualization with Python Laboratory Manual

Program 1b. Develop a python program to check whether a given number is palindrome or
not and also count the number of occurrence of each digit in the input number.

APPLICATIONS / IMPORTANCE:

1. Data Validation – Palindrome checks are used in error detection, validation of IDs,
barcodes, and palindromic sequences.
2. Digital Forensics – Helps in analysing repeated digit patterns (useful in cryptography and
security).
3. Pattern Recognition – Identifying symmetry in numbers is useful in algorithms and
computational mathematics.
4. Banking & Finance – Checking digit occurrences can be used in fraud detection or
transaction analysis.
5. Competitive Exams / Coding Interviews – Palindrome problems are common in coding
assessments.

SOURCE CODE:

val = int(input("Enter a value:")) # Takes integer input

str_val = str(val) # Converts the integer to a string

if str_val == str_val[::-1]: # Checks if the string is a palindrome

print("Number is palindrome") # Prints if the number is a palindrome

else:

print("Number is not a palindrome") # Prints if the number is not a palindrome

# Counts the occurrence of each digit in the number

for i in range(10): # Iterates through digits 0 to 9

if str_val.count(str(i)) > 0: # Checks if the digit appears in the string

print(str(i), "appears", str_val.count(str(i)), "times") # Prints the digit and its


occurrence count

SAMPLE INPUT
INPUT
Enter a value: 12221
Dept. ofOUTPUT
Information Science & Engineering. DBIT, Bengaluru Page 3
B24IS374 – Data Visualization with Python Laboratory Manual

Number is palindrome
1 appears 2 times
2 appears 3 times

INPUT
Enter a value:1234
OUTPUT
Number is not a palindrome
1 appears 1 times
2 appears 1 times
3 appears 1 times
4 appears 1 times.

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 4


B24IS374 – Data Visualization with Python Laboratory Manual

Program 2a. Defined as a function F as Fn=Fn-1+Fn-2, write a python program which


accepts a value for N (where N>0)as input and pass this value to the function. Display the
suitable error message if the condition for input value is not allowed.
APPLICATIONS / IMPORTANCE: Application of this Program:

1. Mathematics – Fibonacci numbers appear in number theory, series, and patterns.


2. Nature & Biology – Models natural phenomena (shell spirals, sunflower seeds,
pinecones).
3. Computer Science – Basis for recursion, dynamic programming, and algorithm design.
4. Search Algorithms – Fibonacci search is used in sorted arrays.
5. Financial Markets – Fibonacci ratios (like 0.618, 1.618) are used in stock trend analysis.

Source code:

def Fibonacci(n):

if n < 0:

print("Incorrect input")

elif n == 0:

return 0

elif n == 1 or n == 2:

return 1

else:

return Fibonacci(n-1) + Fibonacci(n-2)

num = int(input("Enter a number: "))

print(Fibonacci(num))
SAMPLE OUTPUT:

INPUT 1
Enter a number: 0
OUPUT
0
INPUT 2
Enter a number: 0
OUPUT
1
INPUT 3
Enter a number :-8
Incorrect input

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 5


B24IS374 – Data Visualization with Python Laboratory Manual

Program 2b. Python program to convert decimal to Binary, Octal and Hexadecimal.

APPLICATIONS / IMPORTANCE: Application of this Program:


1. Mathematics & Computer Science – Fibonacci numbers appear in algorithms,
recursion, and dynamic programming.
2. Nature & Biology – Models growth patterns in plants, shells, pinecones, sunflower
spirals, etc.
3. Data Structures & Algorithms – Used in search techniques (Fibonacci search), heap
structures, and optimization.
4. Cryptography & Security – Fibonacci-based sequences are used in pseudorandom
number generation and encryption.
5. Financial Markets – Fibonacci ratios (e.g., 0.618) are widely used in stock market
technical analysis.

Source code:

def bin2dec(val):

return int(val, 2) # convert binary to decimal

def oct2hex(val):

return hex(int(val, 8)) # convert octal to hex

try:

num1 = input("Enter a binary number: ")

print("Decimal value:", bin2dec(num1))

except ValueError:

print("Invalid literal in input with base 2")

try:

num2 = input("Enter an octal number: ")

print("Hexadecimal value:", oct2hex(num2))

except ValueError:

print("Invalid literal in input with base 8")

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 6


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT 1
Enter a binary number: 1010
Decimal value: 10
Enter an octal number: 77
Hexadecimal value: 0x3f

OUTPUT 2
enter a binary number: 1111
Decimal value: 15
Enter an octal number: 99
Invalid literal in input with base 8

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 7


B24IS374 – Data Visualization with Python Laboratory Manual

3a. Find number of words, digits, uppercase, lowercase letters from a given sentence.
APPLICATIONS / IMPORTANCE: Application of this Program:
1. Text Processing & NLP – Used in text analysis, preprocessing for AI/ML models,
and natural language processing.
2. Data Validation – Helps check format of passwords, usernames, and secure text
(e.g., must contain uppercase, lowercase, and digits).
3. Education & Research – Useful for analyzing documents, essays, or assignments.
4. Search Engines / Indexing – Helps count keywords and analyze content structure.
5. Cybersecurity – Applied in password strength checking by analyzing presence of
digits/letters.

Source code:

S = input("Enter Sentence: ")


w, d, u, l = 0, 0, 0, 0
# count words
l_w = [Link]()
w = len(l_w)
# count digits, uppercase, lowercase
for C in S:
if [Link]():
d += 1
elif [Link]():
u += 1
elif [Link]():
l += 1
print("No. of words:", w)
print("No. of uppercase letters:", u)
print("No. of digits:", d)
print("No. of lowercase letters:", l)

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 8


B24IS374 – Data Visualization with Python Laboratory Manual

SAMPLE OUTPUT:

INPUT
Enter Sentence: Helloworl1d Enter Sentence: Hello world1234
No. of words: 2
No. of uppercase letters: 1
No. of digits: 4
No. of lowercase letters: 9

OUTPUT
No. of words: 1
No. of uppercase
letters: 2 No. of
digits: 3
No. of lowercase letters 8

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 9


B24IS374 – Data Visualization with Python Laboratory Manual

Program 3b. Write a python program to find the string similar between two strings

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Plagiarism Detection – Helps in checking text similarity in documents.


2. Search Engines – Used in keyword matching and query optimization.
3. DNA / Protein Sequence Matching – Similarity checks are widely used in
bioinformatics.
4. Cybersecurity – Useful in detecting common patterns in passwords or encrypted
strings.
5. Machine Learning & NLP – Important for preprocessing, text similarity, and
recommendation systems.

Source code:

str1=input("Enter first string:\n") str2=input("Enter


second string:\n") if len(str2)<len(str1):
short=len(str2) long=len(str1)
else:
short=len(str1) long=len(str2)
matchcount=0
for i in range(short): if str1[i]==str2[i]:
matchcount+=1
print("Similar between two strings:")
print(matchcount/long)
SAMPLE OUTPUT:

INPUT:
Enter first string: Python
Enter second string: Programming
OUTPUT: Similar between two strings:0.09090909090909091
INPUT:
Enter first string: hello
Enter second string: hello world
OUTPUT:
Similarity between two strings: 0.45454545454545453

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 10


B24IS374 – Data Visualization with Python Laboratory Manual

INPUT:
Enter first string: Python
Enter second string: Python
OUTPUT:
Similarity between two strings:1.0

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 11


B24IS374 – Data Visualization with Python Laboratory Manual

Program 4a. write a python program to demonstrate, how to draw a bar plot using matplotlib.

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Data Visualization – Easy way to represent categorical data (e.g., sales, marks,
population).
2. Comparative Analysis – Helps compare different groups/categories at a glance.
3. Business & Finance – Used in dashboards for revenue, expenses, and growth
analysis.
4. Education & Research – Representing student scores, survey results, experimental
data.
5. Decision Making – Bar plots simplify complex datasets for quick insights.

Source code:

import [Link] as plt

Categories=['0-10','10-20','20-30','30-40','40-50']
value=[55,48,25,68,90]
[Link](Categories,value,color='green)
[Link]('overs')
[Link]('runs')
[Link]("Bars plot showing runs scored in an ODI match")
[Link]()

OUTPUT

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 12


B24IS374 – Data Visualization with Python Laboratory Manual

Program 4b. Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Relationship Analysis – Shows correlation between two variables (positive, negative, or


none).
2. Data Science & Machine Learning – Helps visualize datasets and trends before modeling.
3. Business Analytics – Used to find relationships (e.g., advertising cost vs sales).
4. Research & Statistics – Detects outliers and unusual data patterns.
5. Quality Control – Identifies relationships between process factors and outcomes.

Source code:

import [Link] as plt


import numpy as np

# Data
countries = ['Brazil', 'Russia', 'India', 'China', 'USA']
population = [213997, 145677, 124571, 457168, 734567]
per_capita_income = [9600, 1160, 2300, 1100, 6500]
# Circle sizes scaled by population
circle_size = [pop/1000 for pop in population]
# Colors based on index
colors = [Link](len(countries))
# Scatter plot
scatter = [Link](population, per_capita_income,
s=circle_size, c=colors, cmap='viridis',
alpha=0.7, label='BRICS nations')
# Annotate each country
for i, country in enumerate(countries):
[Link](country,
(population[i], per_capita_income[i]),
textcoords='offset points',
xytext=(0, 5), ha='center')
# Add colorbar
[Link](scatter,
Dept. of Information label='Index') DBIT, Bengaluru
Science & Engineering. Page 13
B24IS374 – Data Visualization with Python Laboratory Manual

# Labels and title


[Link]('Population (in thousands)')
[Link]('Per capita income (USD)')
[Link]('Population vs Per Capita Income of BRICS Nations')
[Link]()

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 14


B24IS374 – Data Visualization with Python Laboratory Manual

Program 5a. write a python program to demonstrate how to draw a histogram plot using
matplotlib.
APPLICATIONS / IMPORTANCE: Application of this Program:

1. Data Analysis – Helps understand the distribution of a dataset (normal, skewed, etc.).
2. Statistics & Research – Used to visualize frequency distribution.
3. Education – Analyzing exam scores, attendance patterns, etc.
4. Business & Finance – Visualizing sales distribution, customer ages, transaction sizes.
5. Machine Learning & AI – Feature distribution analysis before training models.

SOURCE CODE:
import [Link] as plt
import numpy as np [Link](42)
student_scores=[Link](loc=70,scale=15,size=100)
[Link](student_scores,bins=20,color='pink',edgecolor='purple')
[Link]('student scores')
[Link]('frequency')
[Link]('distribution of student scores')
[Link]()

OUTPUT

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 15


B24IS374 – Data Visualization with Python Laboratory Manual

Program 5b(i). Write a python program to demonstrate how to draw a pie chart using
matplotlib.

APPLICATIONS / IMPORTANCE: Application of this Program:


1. Data Representation – Shows proportional distribution of data.
2. Business & Finance – Market share, revenue breakdown, budget allocation.
3. Education – Visualizing student performance or attendance percentage.
4. Survey Analysis – Representing poll results or customer preferences.
5. Decision Making – Helps managers quickly interpret percentage contributions.

SOURCE CODE:
import [Link] as plt
countries=['brazil','germany','italy','usa','africa','france','england','spain'] wins=[5,4,4,3,2,2,1,1]
colors=['yellow','magenta','green','blue','pink','purple','red','cyan']
[Link](wins,labels=countries,autopct='%1.1f%%',colors=colors,startangle=90,explode=[0.2,
0.2,0.2,0.2, 0.2,0.2,0.2,0.2],shadow=True)

[Link]('FIFA WORLD CUP WINS BY COUNTRY')

[Link]('equal') [Link]()

OUTPUT

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 16


B24IS374 – Data Visualization with Python Laboratory Manual

Program 5b(ii) Write a python program to demonstrate, how to draw a pie chart using
matplotlib, display values instead of percentages.

APPLICATIONS / IMPORTANCE: Application of this Program:


1. Education – Display actual marks scored in subjects instead of percentage contribution.
2. Business & Finance – Show real revenue figures per department rather than percentages.
3. Project Management – Resource allocation in terms of actual hours or cost.
4. Survey & Polling – Display exact number of respondents per choice.
5. Decision Making – Helps stakeholders see real quantities rather than just ratios.

SOURCE CODE:
import [Link] as plt
countries=['brazil','germany','italy','usa','africa','france','england','spain']
wins=[5,4,4,3,2,2,1,1]
colors=['yellow','magenta','green','blue','pink','purple','red','cyn']
def make_autopct(values):
def my_autopct(pct):
total=sum(values)
val=int(round(pct*total/100.0))
return'{v:d}'.format(v=val)
return my_autopct
[Link](wins,labels=countries,autopct=make_autopct
(wins),colors=colors,startangle=90,explode=[0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2],shadow=True)
[Link]('FIFA WORLD CUP WINS BY COUNTRY')
[Link]('equal')
[Link]()

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 17


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 18


B24IS374 – Data Visualization with Python Laboratory Manual

Program 6a(i) Write a python program to illustrate linear plotting using matplotlib.

APPLICATIONS / IMPORTANCE: Application of this Program:


1. Mathematics & Science – Represent linear equations, proportional relationships.
2. Engineering – Analyze straight-line trends like speed vs time, current vs voltage.
3. Economics & Business – Used for cost, profit, demand, and revenue analysis.
4. Education – Helps students understand algebraic equations visually.
5. Data Analysis – Useful to detect simple proportional or linear trends in datasets.

SOURCE CODE:

import [Link] as plt

overs=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

runs_scored=[0,7,12,20,39,49,61,83,86,97,113,116,123,137,145,163,172,192,198,19,203]

[Link](overs,runs_score) [Link]('overs')

[Link]('Runs scored')

[Link]('Run scoring in an T20 cricket match')

[Link](True)

[Link]()

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 19


B24IS374 – Data Visualization with Python Laboratory Manual

Program 6a(ii) Write a python program to illustrate linear plotting with line formatting using
matplotlib.

APPLICATIONS / IMPORTANCE: Application of this Program:


1. Clarity in Visualization – Different line styles make multiple graphs easier to distinguish.
2. Scientific Research – Used for highlighting different experimental results on the same
graph.
3. Business & Finance – Distinguishing multiple trends like profit, cost, revenue.
4. Education – Helps students compare different linear equations visually.
5. Professional Reports – Improves readability and presentation quality.

SOURCE CODE:
import [Link] as plt
# Data
overs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
runs_scored =
[0,7,12,20,39,49,61,83,86,97,113,116,123,137,145,163,172,192,198,198,203]
# Plot with formatting
[Link](
overs, runs_scored,
marker='X',
linestyle='dashed',
color='green',
linewidth=2,
markerfacecolor='blue',
markersize=8
)
# Labels and title
[Link]('Overs', color='green')
[Link]('Runs Scored')
[Link]('Run Scoring in a T20 Cricket Match')
# Grid
[Link](True)
# Show plot
[Link]()

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 20


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 21


B24IS374 – Data Visualization with Python Laboratory Manual

Program 7. Write a Python program which explains uses of customizing seaborn plots with
Aesthetic functions.

APPLICATIONS / IMPORTANCE: Application of this Program:


1. Improved Readability – Adjust fonts, grids, and colors for clarity in reports.
2. Professional Data Visualization – Make plots publication-ready for research papers.
3. Business Dashboards – Enhance aesthetics to present trends to stakeholders.
4. Education & Teaching – Better visuals help in explaining concepts clearly.
5. Data Science & Machine Learning – Easier comparison of variables when visuals are
clear and color-coded.

SOURCE CODE:
import numpy as np
import [Link] as plt
import seaborn as sns
# Function to plot sine curves
def sinplot(n=10):
x = [Link](0, 14, 100)
for i in range(1, n + 1):
[Link](x, [Link](x + i * 0.5) * (n + 2 - i))
# Apply Seaborn theme and context
sns.set_theme()
sns.set_context("notebook", font_scale=1.5, rc={"[Link]": 2.5})
# Call function
sinplot()
[Link]("Seaborn plots with Aesthetic functions")
[Link]()

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 22


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 23


B24IS374 – Data Visualization with Python Laboratory Manual

Program 8 a) Write a Python program for plotting different types of plots using Bokeh.

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Interactive Dashboards – Better than static plots for data exploration.


2. Web Integration – Easily embed visualizations in websites and apps.
3. Data Science & Business Analytics – Helps stakeholders explore data interactively.
4. Research & Reports – Enables zoom, hover, and pan for detailed analysis.
5. Big Data Visualization – Scales well with large datasets compared to static libraries.

SOURCE CODE:

import numpy as np

from [Link] import gridplot from


[Link] import figure, show
x = [Link](0, 4*[Link],
100) y = [Link](x)

TOOLS =

"pan,wheel_zoom,box_zoom,reset,save,box_select" p1 =

figure(title="Example 1", tools=TOOLS)

[Link](x, y, legend_label="sin(x)")
[Link](x, 2*y, legend_label="2*sin(x)", color="orange")
[Link](x, 3*y, legend_label="3*sin(x)", color="green")

[Link] = 'Markers'

p2 = figure(title="Example 2", tools=TOOLS)

[Link](x, y, legend_label="sin(x)")
[Link](x, y, legend_label="sin(x)")

[Link](x, 2*y, legend_label="2*sin(x)",


line_dash=(4, 4), line_color="orange", line_width=2)

[Link](x, 3*y, legend_label="3*sin(x)", fill_color=None,


line_color="green") [Link](x, 3*y, legend_label="3*sin(x)",
line_color="green")

[Link] = 'Lines'

show(gridplot([p1, p2], ncols=2, width=400, height=400))

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 24


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 25


B24IS374 – Data Visualization with Python Laboratory Manual

Program 9. Write a Python program to draw 3D Plots using Plotly Libraries.

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Scientific Research – Visualizing 3D surfaces, waves, and experimental results.


2. Engineering – 3D modelling of stress, temperature, and fluid dynamics.
3. Data Science – Multivariable data visualization to detect trends.
4. Geography & Geology – Terrain mapping, elevation plots.
5. Finance & Economics – 3D visualization of multi-factor models.

SOURCE CODE:
import
plotly.graph_objects as go
import numpy as np
# Generate sample 3D
data
x = [Link](-5, 5, 100)
y = [Link](-5, 5, 100)
x, y = [Link](x, y)
z = [Link]([Link](x**2 +y**2))
# Create a 3D surface plot
fig = [Link](data=[[Link](z=z, x=x, y=y)])
# Customize layout
fig.update_layout(
scene=dict(
xaxis_title='X Axis',
yaxis_title='Y Axis',
zaxis_title='Z Axis'
),
margin=dict(l=0,
r=0,b=0,t=40),
title='3D Surface Plot of sin(sqrt(x^2+y^2))')
# Display the 3D surface
plot
[Link]()

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 26


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 27


B24IS374 – Data Visualization with Python Laboratory Manual

Program 10a. Write a Python program to draw Time Series using Plotly Libraries.

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Business & Finance – Track stock prices, company revenue, or customer trends.
2. Weather Forecasting – Analyze temperature, rainfall, or wind speed over time.
3. Healthcare – Patient monitoring (heart rate, blood pressure trends).
4. Economics – GDP growth, inflation, unemployment rates over time.
5. IoT & Sensors – Real-time monitoring of devices and networks.

SOURCE CODE:

The provided Python script showcases the use of the Plotly Express library to create an
interactive line plot depicting the exchange rate between the US Dollar and the Indian Rupee
over [Link] script uses the Pandas library to read currency conversion data from a CSV file
(‘CUR_DLR_INR.csv’). We can download the csv file given above.

import pandas as pd
import [Link] as px
# Read CSV file (must have columns 'DATE' and 'RATE')
dollar_conv = pd.read_csv('CUR_DLR_INR.csv')
# Create time series plot
fig = [Link](
dollar_conv,
x='DATE',
y='RATE',
title='Dollar vs Rupee Exchange Rate',
markers=True
)
# Show plot
[Link]()

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 28


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 29


B24IS374 – Data Visualization with Python Laboratory Manual

Program10b. Write a Python program for creating Maps using Plotly Libraries

APPLICATIONS / IMPORTANCE: Application of this Program:

1. Geographical Data Analysis – Helps visualize global or regional datasets like population, GDP,
literacy rate, etc.
2. Business Insights – Companies can track sales, customers, or branch distributions across
locations.
3. Epidemiology – Used to map the spread of diseases (e.g., COVID-19 cases across countries).
4. Environmental Studies – Track climate data, deforestation, pollution levels on maps.
5. Education & Research – Useful for teaching geography, demographics, and socio-economic
trends interactively.
6. Data Journalism – Create interactive maps to explain world events and trends in news articles.

SOURCE CODE:

import [Link] as px

import pandas as pd

# Import data from GitHub

data =
pd.read_csv('[Link]
with_codes.csv')

# Create basic choropleth map

fig = [Link](

data,

locations='iso_alpha',

color='gdpPercap',

hover_name='country',

projection='natural earth',

title='GDP per Capita by Country'

[Link]()

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 30


B24IS374 – Data Visualization with Python Laboratory Manual

OUTPUT:

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 31


B24IS374 – Data Visualization with Python Laboratory Manual

SAMPLE VIVA QUESTIONS

1 What is a bar plot, and when is it used?

2 How do you create a simple bar plot in Matplotlib?

3 What is a scatter plot, and what kind of data is it best suited for?

4 Describe the key differences between a bar plot and a scatter plot.

5 How can you customize the color of bars in a bar plot?

6 How do you add labels to the axes in a bar plot?

7 What command is used to display a plot in Matplotlib?

8 How would you add a title to a scatter plot?

9 What is the purpose of a legend in a scatter plot?

10 Explain how to adjust the size of points in a scatter plot.


11 What is a histogram, and what does it show about the data?
12 How do you determine the number of bins in a histogram?
13 Explain the difference between a histogram and a bar chart.
14 How do you plot multiple histograms in a single figure?
15 How would you customize the bin size in a histogram?
16 What is a pie chart, and when would it be useful?
17 How do you label each section in a Matplotlib pie chart?
18 How can you create a pie chart with custom colors?
19 How do you make a section of a pie chart stand out using Matplotlib?
20 Explain the importance of the 'explode' parameter in a pie chart.
21 What is linear plotting, and where is it commonly used?
22 How do you create a simple line plot in Matplotlib?
23 What are the main parameters for customizing a line plot?
24 Explain how to plot multiple lines in a single chart.
25 What is a subplot, and why is it useful?
26 How do you add multiple subplots to a figure in Matplotlib?
27 How do you adjust the spacing between subplots?
28 What are some common uses of stacked plots?
29 How would you change the colors in a stacked plot?
30 What is Seaborn, and how does it differ from Matplotlib?
31 How do you import Seaborn in Python?
32 What are aesthetic functions in Seaborn?

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 32


B24IS374 – Data Visualization with Python Laboratory Manual

33 How can you customize the style of a plot in Seaborn?


34 How do you adjust the color palette in Seaborn plots?
35 What is the function used to set a background grid in Seaborn?
36 Describe the role of annotations in a Bokeh line graph.

Dept. of Information Science & Engineering. DBIT, Bengaluru Page 33

You might also like