Data Visualization With Python Lab Manual
Data Visualization With Python Lab Manual
TECHNOLOGY
(An Autonomous Institute, Affiliated to VTU, Belagavi) Mysuru
Road, Kumbalagodu, Bengaluru – 560 074.
Scheme 2024
[Link] G M
Manual Prepared by [Link] A B
Dr. B K Raghavendra
Approved by
HOD - Dept. of ISE, DBIT
Table of Contents
3 POs ii
Empower the students to thrive for excellence in the area of Information Science and
Engineering to use technology for sustainable development for social needs.
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
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
LAB RUBRICS
Rubrics for Evaluation of Lab Record:
[v]
3 Viva 15
100
TOTAL (scaled down to 20)
MARKS
[vi]
Rubrics for Evaluation of Internal Test:
[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
2. Fair Assessment – Ensures students are not penalized heavily for one bad test day,
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
SOURCE CODE:
min_score=test2 else:
min_score=test3
average=(test1+test2+test3-min_score)/2
SAMPLE OUTPUT
INPUT
Enter test1 marks:99
OUTPUT
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:
else:
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.
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:
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
Program 2b. Python program to convert decimal to Binary, Octal and Hexadecimal.
Source code:
def bin2dec(val):
def oct2hex(val):
try:
except ValueError:
try:
except ValueError:
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
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:
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
Program 3b. Write a python program to find the string similar between two strings
Source code:
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
INPUT:
Enter first string: Python
Enter second string: Python
OUTPUT:
Similarity between two strings:1.0
Program 4a. write a python program to demonstrate, how to draw a bar plot using matplotlib.
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:
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
Program 4b. Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.
Source code:
# 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
OUTPUT:
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
Program 5b(i). Write a python program to demonstrate how to draw a pie chart using
matplotlib.
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]('equal') [Link]()
OUTPUT
Program 5b(ii) Write a python program to demonstrate, how to draw a pie chart using
matplotlib, display values instead of percentages.
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]()
OUTPUT:
Program 6a(i) Write a python program to illustrate linear plotting using matplotlib.
SOURCE CODE:
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](True)
[Link]()
OUTPUT:
Program 6a(ii) Write a python program to illustrate linear plotting with line formatting using
matplotlib.
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]()
OUTPUT:
Program 7. Write a Python program which explains uses of customizing seaborn plots with
Aesthetic functions.
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]()
OUTPUT:
Program 8 a) Write a Python program for plotting different types of plots using Bokeh.
SOURCE CODE:
import numpy as np
TOOLS =
"pan,wheel_zoom,box_zoom,reset,save,box_select" p1 =
[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'
[Link](x, y, legend_label="sin(x)")
[Link](x, y, legend_label="sin(x)")
[Link] = 'Lines'
OUTPUT:
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]()
OUTPUT:
Program 10a. Write a Python program to draw Time Series using Plotly Libraries.
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]()
OUTPUT:
Program10b. Write a Python program for creating Maps using Plotly Libraries
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
data =
pd.read_csv('[Link]
with_codes.csv')
fig = [Link](
data,
locations='iso_alpha',
color='gdpPercap',
hover_name='country',
projection='natural earth',
[Link]()
OUTPUT:
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.