DataVisualizationUsingPython LAB MANUAL
DataVisualizationUsingPython LAB MANUAL
LABORATORY MANUAL
LABORATORY
Prepared By
Dr. Vidya Dandagi
Prof.Anusha Chogund
Approved By
Dr. Uttam Patil
HOD, CSE
INSTITUTIONAL MISSION AND VISION
Vision
Mission
• To provide work culture that facilitates effective teaching-learning process and lifelong
learning skills
• To promote innovation, collaboration and leadership through best practices
• To foster industry-institute interaction resulting in entrepreneurship skills and employment
opportunities
Department of Computer Science & Engineering
Vision
Mission
PO2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one‘s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PSO1: Apply mathematical and scientific skills in the area of computer science and engineering to
design, develop, analyze software and hardware based systems.
PSO2: Provide solutions using networking and database administration skills, and address the needs
of environmental and societal issues through entrepreneurial practices.
1. To produce graduates who have a strong foundation of knowledge and Engineering skills
that will enable them to have successful career in the field of computer science and
engineering.
2. To expose graduates to professional and team building skills along with ideas of innovation
and invention.
Course objectives:
CLO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications
CLO 2. Using Python programming language to develop programs for solving real-
world problems CLO 3. Implementation of Matplotlib for drawing different Plots
CLO 4. Demonstrate working with Seaborn, Bokeh.
CLO 5. Working with Plotly for 3D, Time Series and Maps.
Experiments
List of problems for which student should develop program and execute in the
Laboratory
1 a) Write a python program to find the best of two test average marks out of three test’s marks
acceptedfrom the user.
b) Develop a Python program to check whether a given number is palindrome or not and
also count the number of occurrences of each digit in the input number.
Datatypes:
https://www.youtube.com/watch?v=gCCVsvgR2KU
Operators:
https://www.youtube.com/watch?v=v5MR5JnKcZI Flow
Control:
https://www.youtube.com/watch?v=PqFKRqpHrjw For
loop: https://www.youtube.com/watch?v=0ZvaDa8eT5s
While loop:
https://www.youtube.com/watch?v=HZARImviDxg
Exceptions:
https://www.youtube.com/watch?v=6SPDvPK38tw
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 >0) as input and pass this value to the function. Display suitable error message if the
conditionfor input value is not followed.
b) Develop a python program to convert binary to decimal, octal to hexadecimal
using functions. Functions:https://www.youtube.com/watch?v=BVfCWuca9nw
Arguments:https://www.youtube.com/watch?v=ijXMGpoMkhQ
Return value: https://www.youtube.com/watch?v=nuNXiEDnM44
3 a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercaseletters and lowercase letters.
b) Write a Python program to find the string similarity between two given strings
Sample Output: Sample Output:
Original string: Original string:
Python Exercises Python
Exercises Python Exercises
Python Exercise
Similarity between two said strings: Similarity between two said strings:1.0
0.967741935483871
Strings: https://www.youtube.com/watch?v=lSItwlnF0eU
String functions: https://www.youtube.com/watch?v=9a3CxJyTq00
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
https://www.youtube.com/watch?v=RRHQ6Fs1b8w&list=PLjVLYmrlmjGcC0B_FP3bkJJ
IPkV5GuZR & index=3
https://www.youtube.com/watch?v=7ABCuhWO9II&list=PLjVLYmrlmjGcC0B_FP3bkJJI
PkV5GuZR& index=4
5 a) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
https://www.youtube.com/watch?v=Qk7caotaQUQ&list=PLjVLYmrlmjGcC0B_FP3bkJJIP
kV5GuZR&i ndex=6
https://www.youtube.com/watch?v=PSji21jUNO0&list=PLjVLYmrlmjGcC0B_FP3bkJJIPk
V5GuZR&in dex=7
7 Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.https://www.youtube.com/watch?v=6GUZXDef2U0
8 Write a Python program to explain working with bokeh line graph using Annotations and Legends.
a) Write a Python program for plotting different types of plots using
Bokeh.https://www.youtube.com/watch?v=HDvxYoRadcA
print("Average of best two test marks out of three test’s marks is", avgMarks)
Output:
Average of best two test marks out of three test’s marks is 92.5
Description:
The provided Python program is designed to calculate the average of the best two test marks out of
three. The user is prompted to input the marks for three tests (test1, test2, and test3). The program
then identifies the two highest test marks using the sorted function in descending order and selects the
top two values. Finally, it calculates the average of these two highest marks and prints the result. This
code is a concise way to determine the average performance based on the two best test scores out of
three.
1 b) Develop a Python program to check whether a given number is palindrome or not and also count
the number of occurrences of each digit in the input number.
Program:
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
Output:
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 2 times
4 appears 2 times
Not a Palindrome
4 appears 2 times
5 appears 2 times
6 appears 2 times
7 appears 1 times
8 appears 1 times
The provided Python script is a versatile program that performs two key tasks: palindrome checking and
character counting.
Palindrome Check:
The script determines whether the entered value is a palindrome, meaning it reads the same backward
as forward.
Character Count:
The script utilizes the Counter class from the collections module to efficiently count the occurrences of
each character in the input string.
It then sorts the keys of the counted dictionary and prints each character along with the number of
times it appears.
The script provides an alternative method using a loop to count the occurrences of each digit (0 to 9) in
the input string.
This script is not only a quick and effective way to check for palindromes but also serves as a handy tool
for analyzing the frequency of characters in a given input. The inclusion of alternative methods
showcases the flexibility of the script, making it a valuable resource for both palindrome detection and
character frequency analysis.
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 >0) as input and pass this value to the function. Display suitable error message if
the condition for input value is not followed.
Program:
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
if num > 0:
else:
print("Error in input")
Output:
1) Enter a number : 8
fn( 8 ) = 13
2) Enter a number : -1
Error in input
Description:
The provided Python script introduces a recursive implementation to calculate terms in the
Fibonacci sequence. Here’s a concise overview:
The script defines a function fn that calculates the nth term in the Fibonacci sequence.
If the input n is 1 or 2, the function returns n - 1.
For n greater than 2, the function recursively calls itself with n-1 and n-2 and returns the sum of the
results.
If a positive integer is provided, the script prints the result of calling the fn function with that
number, representing the nth term in the Fibonacci sequence.
If the entered value is not a positive integer, it prompts the user to enter a value greater than 0.
If a non-numeric value is entered, it catches the ValueError and suggests trying with a numeric
value.
This script serves as a simple yet illustrative example of a recursive function for computing Fibonacci
sequence terms, offering insights into recursive algorithms and user input handling in Python.
2 b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
Program:
def bin2Dec(val):
rev = val[::-1]
dec = 0
i=0
dec += int(dig) * 2 ** i
i += 1
return dec
def oct2Hex(val):
rev = val[::-1]
dec = 0
i=0
dec += int(dig) * 8 ** i
i += 1
list = []
while dec != 0:
list.append(dec % 16)
dec = dec // 16
nl = []
nl.append(str(elem))
else:
hex = "".join(nl)
return hex
print(bin2Dec(num1))
print(oct2Hex(num2))
Output:
14
1BD
Description:
This Python script includes two functions bin2Dec and oct2Hex for converting binary to decimal and
octal to hexadecimal, respectively. The script takes user input for binary and octal numbers and
converts them using these functions. Here’s a brief description:
Conversion Functions:
The bin2Dec function converts a binary number to decimal using the int() function with base 2.
The oct2Hex function converts an octal number to hexadecimal using the int() function with base 8.
The script includes try-except blocks to catch ValueError in case of invalid input.
It prompts the user for a binary and an octal number, converts them, and prints the results.
Program:
for ch in sentence:
digCnt += 1
upCnt += 1
loCnt += 1
print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt, "lower case letters")
Output:
Enter a sentence : The earth has 7 continents namely Asia, Africa, North America, South America,
Europe, Australia and Antarctica
This sentence has 1 digits 10 upper case letters 79 lower case letters
Description:
The above Python program is designed to analyse a user-inputted sentence, providing information
on the number of words, digits, uppercase letters, and lowercase letters in the given text. Here’s a
concise overview:
Word Count:
The script splits the input sentence into words and prints the count of words in the sentence.
Character Analysis:
It then iterates through each character in the sentence.
The script counts the number of digits, uppercase letters, and lowercase letters using the string
module.
Print Results:
Finally, it prints the counts of digits, uppercase letters, and lowercase letters in the given sentence.
This script serves as a versatile tool for quickly extracting key statistics from a user-provided
sentence, offering insights into the composition of the text in terms of words and character types.
3 b) Write a Python program to find the string similarity between two given strings.
Program:
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print((matchCnt / long)*100)
Output:
Enter String 1:
Iceberg
Enter String 2:
Icecream
37.5
Description:
The provided Python script is designed to compare the similarity between two user-inputted strings.
The user is prompted to input two strings, and the script, after converting them to lowercase for
case-insensitive comparison, calculates the similarity by counting the matching characters at
corresponding positions. The similarity is then expressed as a ratio relative to the length of the
longer string. Here’s a brief overview:
User Input:
String Comparison:
The script then iterates through characters at corresponding positions and counts the matches.
Similarity Ratio:
The similarity between the two strings is calculated as the ratio of the count of matching characters
to the length of the longer string.
Alternative Solution :
The script includes an alternative solution using the SequenceMatcher class from the difflib library,
demonstrating a different approach to calculating string similarity.
This script offers a straightforward way to measure the similarity between two strings and presents
an alternative solution using Python libraries for a comparative understanding. It’s a useful tool for
users interested in comparing the likeness of textual data.
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
plt.xlabel('Overs')
plt.ylabel('Runs')
plt.show()
Output:
Description:
The provided Python script utilizes the matplotlib library to create a bar plot showcasing runs scored
in an ODI (One Day International) cricket match. Here’s a concise overview:
Sample Data:
The script uses sample data representing runs scored in specific overs during an ODI cricket match.
Matplotlib Plotting:
The bar function is used to plot the data, where categories represent overs, and values represent
runs scored.
The script adds labels to the x-axis (Overs) and y-axis (Runs).
It includes a title, ‘Bar Plot Showing Runs scored in an ODI Match,’ to provide context to the plot.
Display:
This script is a straightforward example of using matplotlib to visualize data in a bar plot. It’s a
valuable resource for individuals interested in creating basic data visualizations, particularly in the
context of cricket statistics.
4 b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
import numpy as np
per_capita_income = [9600, 11600, 2300, 11000, 6500] # Per capita income in USD
circle_size = [pop / 1000000 for pop in population] # Scaling down for better visualization
colors = np.arange(len(countries))
# Add colorbar
plt.colorbar(scatter, label='Index')
plt.xlabel('Population')
plt.show()
Output:
Description:
The provided Python script employs the matplotlib library, along with numpy, to create a scatter
plot visualizing population against per capita income for BRICS nations. Here’s a concise overview:
Sample Data:
The script uses hypothetical data for BRICS nations, including population and per capita income.
Circle sizes are scaled down from population values to enhance visualization.
Color Assignment:
Scatter Plot:
The scatter function is used to create a scatter plot with varying circle sizes and colors.
Annotations:
Each point on the plot is annotated with the country name for clarity.
Colorbar:
A colorbar is added to the plot, providing a reference for the color index.
Labels for the x-axis, y-axis, and a title are included to provide context.
Display:
This script serves as an excellent example of using matplotlib for creating informative and visually
appealing scatter plots, especially for comparing socio-economic indicators among different
countries. It can be helpful for readers interested in data visualization and analysis.
5 b) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib
import numpy as np
np.random.seed(42)
plt.xlabel('Student Scores')
plt.ylabel('Frequency')
plt.show()
Output:
Description:
The provided Python script utilizes the matplotlib library and numpy to generate a histogram plot
illustrating the distribution of student scores. Here’s a concise overview:
The script generates example data representing student scores using a normal distribution
(np.random.normal).
Histogram Plot:
It creates a histogram plot using the hist function, where student_scores is the data array, bins
determines the number of bins, and color sets the fill color while edgecolor sets the color of bin
edges.
The script adds labels to the x-axis (Student Scores) and y-axis (Frequency).
Display:
This script serves as a simple yet effective demonstration of using matplotlib to visualize the
distribution of a dataset, making it suitable for readers interested in introductory data visualization
techniques. It’s especially valuable for those learning to interpret histograms in the context of
student scores or similar datasets.
5 b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
# Add title
plt.axis('equal') # Equal aspect ratio ensures that the pie chart is circular.
plt.show()
Output:
Description:
The provided Python script utilizes the matplotlib library to create a visually appealing pie chart
representing the number of FIFA World Cup wins for different countries. Here’s a concise overview:
Data Representation:
The script uses hypothetical data representing the number of FIFA World Cup wins for different
countries.
It creates a pie chart using the pie function, where wins is the data array, labels are country names,
and autopct formats the percentage display.
Different colors are assigned to each country using the colors parameter.
The pie chart is enhanced with features such as a start angle, explode effect, and shadow.
Title:
The script adds a title to the pie chart, enhancing the overall context.
Display:
This script serves as a clear and concise example of using matplotlib to create visually engaging pie
charts, making it suitable for readers interested in representing categorical data, such as FIFA World
Cup wins, in a graphical format.
6 a) Write a Python program to illustrate Linear Plotting using Matplotlib.
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]
plt.plot(overs, runs_scored)
plt.xlabel('Overs')
plt.ylabel('Runs scored')
plt.grid(True)
plt.show()
Output:
Description:
The provided Python script utilizes the matplotlib library to create a linear plot representing the run
rate in a hypothetical T20 cricket match. Here’s a concise overview:
Hypothetical Data:
The script uses hypothetical data representing the number of runs scored in each over of a T20
cricket match.
Linear Plot:
It creates a linear plot using the plot function, where overs is on the x-axis and runs_scored is on the
y-axis.
The script adds labels to the x-axis (Overs) and y-axis (Runs scored).
A title, ‘Run Scoring in a T20 Cricket Match,’ provides context to the plot.
Grid:
Display:
This script serves as a straightforward example of using matplotlib to visualize run scoring trends in a
T20 cricket match, making it suitable for readers interested in representing time-dependent data in
a graphical format.
6 b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib.
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]
plt.ylabel('Runs scored')
plt.grid(True)
plt.show()
Output:
Description:
The provided Python script, an extension of the previous T20 cricket match run rate plot, customizes
the appearance of the plot with specific markers, line styles, colors, and label styles. Here’s a concise
overview:
The plot function is customized with parameters such as marker, linestyle, color, linewidth,
markerfacecolor, and markersize to control the appearance of the plot.
The script adds labels to the x-axis (Overs) and y-axis (Runs scored) with specific color styling.
Grid:
Display:
The show function is called to display the generated customized linear plot.
This script is an excellent example for readers looking to customize plot aesthetics in matplotlib for a
more visually appealing representation of data. It’s especially helpful for those interested in
enhancing the clarity and style of their data visualizations.
7 ) Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.
import numpy as np
def sinplot(n=10):
sns.set_theme()
#sns.set_context("talk")
sinplot()
plt.show()
Output:
Description:
The provided Python script utilizes the seaborn library, in conjunction with numpy and matplotlib, to
create a series of sine wave plots with customized aesthetics. Here’s a concise overview:
Data Generation:
Seaborn Integration:
The context is set to “notebook” with customized font scaling and line width (set_context).
Customized Aesthetics:
The sinplot function generates multiple sine wave plots with varying frequencies and amplitudes.
The script adds a title to the plot, ‘Seaborn Plots with Aesthetic Functions.’
This script serves as an illustrative example of how seaborn can be used to enhance the aesthetics of
data visualizations, providing readers with insights into customizing plot styles and themes for more
visually appealing results. It’s particularly useful for those looking to leverage seaborn for improved
aesthetics in their data analysis and visualization workflows.
8 a) Write a Python program to explain working with Bokeh line graph using Annotations
and Legends.
b) Write a Python program for plotting different types of plots using Bokeh.
import numpy as np
y = np.sin(x)
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p1.circle(x, y, legend_label="sin(x)")
p1.legend.title = 'Markers'
p2.circle(x, y, legend_label="sin(x)")
p2.line(x, y, legend_label="sin(x)")
p2.legend.title = 'Lines'
The provided Python script demonstrates the use of the Bokeh library to create interactive data
visualizations with multiple plots. Here’s a concise overview:
Data Generation:
The script generates example data (x and y) using NumPy to represent sine waves.
Interactive Tools:
Bokeh’s interactive tools (TOOLS) are enabled for features like pan, zoom, reset, and save.
Multiple Plots:
Two separate plots (p1 and p2) are created with different visualizations, including circles, lines, and
markers.
Grid Layout:
Interactive Display:
The show function is called to display the grid layout, enabling interactive exploration.
This script serves as an introduction to using Bokeh for creating interactive visualizations with
multiple plots, making it suitable for readers interested in interactive data exploration and
visualization techniques.
9) Write a Python program to draw 3D Plots using Plotly Libraries.
import plotly.graph_objects as go
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
# Customize layout
fig.update_layout(scene=dict(
xaxis_title='X Axis',
yaxis_title='Y Axis',
zaxis_title='Z Axis'),
fig.show()
Description:
This program generates a 3D surface plot of the function z = sin(sqrt(x2+y2)). You can modify the
function or provide your own data to create different types of 3D plots. The visualization will be
interactive, allowing you to rotate and explore the plot.
In this Python program, we leverage the power of Plotly Express to visualize the economic evolution
of Asian countries over time. The dataset used is Gapminder, a comprehensive collection of global
development indicators. The focus is specifically on the Asian continent.
Import Libraries:
We start by importing the necessary libraries, including plotly.express for interactive visualizations.
Data Loading:
We load the Gapminder dataset and filter it to include only Asian countries.
3D Line Plot:
The x-axis represents the GDP per capita (gdpPercap), the y-axis represents the population (pop),
and the z-axis represents the year (year).
Interactive Exploration:
The resulting plot is interactive, allowing users to zoom, pan, and hover over data points to explore
specific details.
Users can observe how GDP per capita and population have changed over the years for various
Asian countries. The color-coded lines help distinguish between different nations.
Output:
10 a) Write a Python program to draw Time Series using Plotly Libraries.
Program:
import pandas as pd
import plotly.express as px
dollar_conv = pd.read_csv('CUR_DLR_INR.csv')
fig.show()
Output:
Description:
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 time. Here’s
a concise overview:
Data Import:
The script uses the Pandas library to read currency conversion data from a CSV file
(‘CUR_DLR_INR.csv’). You can download the csv file given above.
Plotly Express:
Plotly Express (px) is employed to create an interactive line plot with the exchange rate data.
Line Plot:
The line function from Plotly Express is used to generate a line plot.
The x-axis represents dates (‘DATE’), and the y-axis represents exchange rates (‘RATE’).
Title:
Interactive Display:
The show method is called on the figure (fig) to display the interactive plot.
This script provides a quick and effective demonstration of using Plotly Express to visualize time-
series data, making it suitable for readers interested in creating interactive and visually appealing
line plots for financial or currency-related datasets.
10 b) Write a Python program for creating Maps using Plotly Libraries.
Program:
import json
import numpy as np
import pandas as pd
import plotly.express as px
#pio.renderers.default = 'browser'
df = pd.read_csv("india_census.csv")
state_id_map = {}
feature["id"] = feature["properties"]["state_code"]
state_id_map[feature["properties"]["st_nm"]] = feature["id"]
df = pd.read_csv("india_census.csv")
#print(df.head())
fig = px.choropleth(
df,
locations="id",
geojson=india_states,
color="Population",
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
Output:
Description:
In this Python program, we leverage Plotly Express to create an insightful choropleth map that
visualizes key demographic indicators across states and union territories in India. The data is sourced
from India’s census, providing a comprehensive overview of population distribution, density, and
sex ratio.
Program Overview:
Import Libraries:
We begin by importing necessary libraries, including json for handling GeoJSON data, numpy for
numerical operations, pandas for data manipulation, and plotly.express for creating interactive
visualizations.
The GeoJSON file representing Indian states is loaded, and census data is read from a CSV file
containing information about population, density, and sex ratio.
Data Preparation:
We create a mapping between state names and their corresponding IDs for seamless integration
with GeoJSON features.
Additional data preprocessing includes converting density values to integers and creating a unique
identifier (id) for each state.
Choropleth Map:
hover_data: Additional information displayed on hover, including density, sex ratio, and population.
Interactive Exploration:
The resulting choropleth map is interactive, allowing users to hover over states to explore
population demographics.
Users can explore and compare population distribution, density, and sex ratio across different states
and union territories in India. This program demonstrates the power of Plotly Express for creating
meaningful and interactive visualizations. The choropleth map provides valuable insights into the
demographic landscape of India.