0% found this document useful (0 votes)
41 views

Data Visualization With Python - Update

Uploaded by

Afreed Shahid
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)
41 views

Data Visualization With Python - Update

Uploaded by

Afreed Shahid
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
You are on page 1/ 19

Data Visualization with Python

(BCS403)

LAB MANUAL
For
III SEMESTER (ISE)
2022 SCHEME

Department of Information Science and Engineering

Prepared By:
Dr.RekhaH
Professor
Department of Information Science and Engineering
SIET Tumkuru
Data Visualization with Python(BCS358D) 2024-2025

Experiments:

SL NO. Name of Program

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 andalso count thenumber of occurrences of each digit in the input number.
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.
3. a) Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters andlowercase letters.
b) Write a Python program to find the string similarity between two given strings
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.
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.
6. a) Write a Python program to illustrate Linear Plotting using Matplotlib.
b) Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.
7. Write a Python program which explains uses of customizing seaborn plots with
Aesthetic functions.

Write a Python program to explain working with bokeh line graph using
8. Annotations and Legends.
a) Write a Python program for plotting different types of plots using Bokeh.

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

10. a) Write a Python program to draw Time Series using Plotly Libraries.
b) Write a Python program for creating Maps using Plotly Libraries.

ISE,SIET2
Data Visualization with Python(BCS358D) 2024-2025

LABORATORYPROGRAMS
1) A)Write a python program to find the best of two test average marks out of
three test’s marks acceptedfrom the user.

PROGRAM:

m1 = int(input("Enter marks for test1 : "))


m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))
if m1 <= m2 and m1 <= m3:
avgMarks = (m2+m3)/2
elif m2 <= m1 and m2 <= m3:
avgMarks = (m1+m3)/2
elif m3 <= m1 and m3 <= m2:
avgMarks = (m1+m2)/2
print("Average of best two test marks out of three test’s marks is", avgMarks)

OUTPUT:

Enter marks for test1 : 45


Enter marks for test2 : 38
Enter marks for test3 : 49
Average of best two test marks out of three test’s marks is 47.0

B)Develop a Python program to check whether a given number is palindrome or


not andalso count the number of occurrences of each digit in the input number.

PROGRAM:

val = int(input("Enter a value : "))


str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");

OUTPUT:

Enter a value : 123321


Palindrome
2 appears 2 times
2appears 2 times
3 appears 2 times

ISE,SIET3
Data Visualization with Python(BCS358D) 2024-2025

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.
PROGRAM:

def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
num = int(input("Enter a number : "))
if num> 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")

OUTPUT:

Enter a number : -1
Error in input
Enter a number : 5
fn(5) = 3

B) Develop a python program to convert binary to decimal, octal to hexadecimal


using functions.

PROGRAM:

def binary_to_decimal(binary):
decimal = 0
for digit in binary:
decimal = decimal * 2 + int(digit)
return decimal

def octal_to_hexadecimal(octal):
decimal = 0
for digit in octal:
decimal = decimal * 8 + int(digit)
hexadecimal = hex(decimal).lstrip("0x").upper()
return hexadecimal

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


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

decimal = binary_to_decimal(binary)
print("The decimal equivalent of", binary, "is:", decimal)

ISE,SIET4
Data Visualization with Python(BCS358D) 2024-2025

hexadecimal = octal_to_hexadecimal(octal)
print("The hexadecimal equivalent of", octal, "is:", hexadecimal)

OUTPUT:

Enter a binary number: 101


Enter an octal number: 25
The decimal equivalent of 101 is: 5
The hexadecimal equivalent of 25 is: 15

ISE,SIET5
Data Visualization with Python(BCS358D) 2024-2025

3) A)Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters andlowercase letters.
PROGRAM:

sentence = input("Enter a sentence: ")


words = digits = upper = lower = 0
# Splitting the sentence using split() method , by default split is by spaces
# Return value - list of strings
split_sentence = sentence.split()
print("The result of split() on input sentence is : \n"+str(split_sentence)+"\n")
words = len(split_sentence )
for c in sentence:
if c.isdigit():
digits = digits + 1
elifc.isupper():
upper = upper + 1
elifc.islower():
lower = lower + 1
print ("No of Words: ", words)
print ("No of Digits: ", digits)
print ("No of Uppercase letters: ", upper)
print ("No of Lowercase letters: ", lower)

OUTPUT:

Enter a sentence: Sira Road Tumkur 572106


The result of split() on input sentence is :
['Sira', 'Road', 'Tumkur', '572106']
No of Words: 4
No of Digits: 6
No of Uppercase letters: 3
No of Lowercase letters: 11

B) Write a Python program to find the string similarity between two given strings.

PROGRAM:

str1 = input("Enter String 1 \n")


str2 = input("Enter String 2 \n")
if len(str2) <len(str1):
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):

ISE,SIET6
Data Visualization with Python(BCS358D) 2024-2025

if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt/long)

OUTPUT:

Enter String 1
Python Exercises
Enter String 2
Python Exercise
Similarity between two said strings:
0.9375

ISE,SIET7
Data Visualization with Python(BCS358D) 2024-2025

4) A)Write a Python program to Demonstrate how to Draw a Bar Plot using


Matplotlib.

PROGRAM:

import matplotlib.pyplot as plt


x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 2, 1]
plt.bar(x, y, color='green')
plt.title('Bar Plot Example')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()

OUTPUT:

B) Write a Python program to Demonstrate how to Draw a Scatter Plot using


Matplotlib.

PROGRAM:

import matplotlib.pyplot as plt


import numpy as np
x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x, y)
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')

ISE,SIET8
Data Visualization with Python(BCS358D) 2024-2025

plt.show()

OUTPUT:

ISE,SIET9
Data Visualization with Python(BCS358D) 2024-2025

5) A)Write a Python program to Demonstrate how to Draw a Histogram Plot using


Matplotlib.

PROGRAM:

import matplotlib.pyplot as plt


import numpy as np
data = np.random.normal(100, 10, 1000)
plt.hist(data, bins=20, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram of Data')
plt.grid(True)
plt.show()

OUTPUT:

B) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.

PROGRAM:

import matplotlib.pyplot as plt


countries = ['Brazil', 'Germany', 'Italy', 'Argentina', 'Uruguay', 'France', 'England', 'Spain']
wins = [5, 4, 4, 3, 2, 2, 1, 1]
colors = ['yellow', 'magenta', 'green', 'blue', 'lightblue', 'blue', 'red', 'cyan']
plt.pie(wins, labels=countries, autopct='%1.1f%%', colors=colors, explode=[0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1,0.1], shadow=True)

ISE,SIET10
Data Visualization with Python(BCS358D) 2024-2025

plt.title('FIFA World Cup Wins by Country')


plt.show()

OUTPUT:

ISE,SIET11
Data Visualization with Python(BCS358D) 2024-2025

6) A) Write a Python program to illustrate Linear Plotting using Matplotlib.

PROGRAM:

import matplotlib.pyplot 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,198,203]
plt.plot(overs, runs_scored)
plt.xlabel('Overs')
plt.ylabel('Runs scored')
plt.title('Run scoring in an T20 Cricket Match')
plt.grid(True)
plt.show()

OUTPUT:

B)Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.

PROGRAM:

import matplotlib.pyplot as plt


x = [1, 2, 3, 4, 5, 6]
y = [3, 7, 9, 11, 14, 18]
plt.plot(x, y, marker='o', linestyle='-', color='b', label='Linear Function: y = 2x')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Formatted Linear Plot Example')
plt.legend()
plt.grid(True)

ISE,SIET12
Data Visualization with Python(BCS358D) 2024-2025

plt.show()

OUTPUT:

ISE,SIET13
Data Visualization with Python(BCS358D) 2024-2025

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

PROGRAM:

import seaborn as sns


# Load a sample dataset
tips = sns.load_dataset("tips")
# Set the aesthetic style of the plot
sns.set(style="whitegrid")
sns.scatterplot(x="total_bill", y="tip", style="time", size="size", data=tips)
sns.despine()
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")
plt.title("Scatter Plot of Total Bill vs Tip")
plt.show()
OUTPUT:

ISE,SIET14
Data Visualization with Python(BCS358D) 2024-2025

8) Write a Python program to explain working with bokeh line graph using
Annotations and Legends.

PROGRAM:

from bokeh.plotting import figure, output_file, show


from bokeh.models import Label
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Output to static HTML file
output_file("line_graph_with_annotations.html")
# Create a figure
p = figure(title="Bokeh Line Graph with Annotations", x_axis_label='X-axis',
y_axis_label='Yaxis')
# Plot the line
p.line(x, y, line_width=2, line_color="blue", legend_label="Line Function: y = 2x")
# Add an annotation
annotation = Label(x=3, y=6, text="Important Point", text_font_size="10pt",
text_color="red")
p.add_layout(annotation)
# Add legend
p.legend.location = "top_left"
p.legend.click_policy = "hide"
# Show the plot
show(p)

OUTPUT:

ISE,SIET15
Data Visualization with Python(BCS358D) 2024-2025

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

PROGRAM:

from bokeh.plotting import figure, show, output_file


from bokeh.layouts import layout
from bokeh.models import ColumnDataSource
import random
import numpy as np

x = list(range(1, 11))
y1 = [random.randint(1, 10) for i in x]
y2 = [random.randint(1, 10) for i in x]

p1 = figure(title="Line Plot", x_axis_label="X-Axis", y_axis_label="Y-Axis", width=400,


height=300)
p1.line(x, y1, line_width=2, line_color="blue")

p2 = figure(title="Scatter Plot", x_axis_label="X-Axis", y_axis_label="Y-Axis", width=400,


height=300)
p2.scatter(x, y2, size=10, color="red", marker="circle")

p3 = figure(title="Bar Plot", x_axis_label="X-Axis", y_axis_label="Y-Axis", width=400,


height=300)
p3.vbar(x=x, top=y1, width=0.5, color="green")

p4 = figure(title="Histogram", x_axis_label="Value", y_axis_label="Frequency",


width=400,height=300)
hist, edges = np.histogram(y1, bins=5)
p4.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="purple",
line_color="black")

plot_layout = layout([[p1, p2], [p3, p4]])


output_file("bokeh_plots.html")
show(plot_layout)

OUTPUT:

ISE,SIET16
Data Visualization with Python(BCS358D) 2024-2025

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

PROGRAM:

import plotly.graph_objs as go
import numpy as np

x = np.linspace(-10, 10, 100)


y = np.linspace(-10, 10, 100)
z = np.sin(np.sqrt(x**2 + y**2))

X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

surface = go.Surface(x=X, y=Y, z=Z, colorscale='viridis')

layout = go.Layout(
title='3D Surface Plot',
scene=dict(
xaxis=dict(title='X Axis'),
yaxis=dict(title='Y Axis'),
zaxis=dict(title='Z Axis')
)
)

fig = go.Figure(data=[surface], layout=layout)


fig.show()

OUTPUT:

ISE,SIET17
Data Visualization with Python(BCS358D) 2024-2025

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

PROGRAM:

import plotly.graph_objects as go
data = [
{'x': [1, 2, 3, 4, 5], 'y': [6, 7, 2, 4, 5]},
{'x': [6, 7, 8, 9, 10], 'y': [1, 3, 5, 7, 9]}
]
fig = go.Figure()
for i in range(len(data)):
fig.add_trace(go.Scatter(x=data[i]['x'], y=data[i]['y'], mode='lines'))
fig.update_layout(title='Time Series', xaxis_title='Time', yaxis_title='Value')
fig.show()

OUTPUT:

B) Write a Python program for creating Maps using Plotly Libraries.

PROGRAM:

import plotly.express as px
# Sample data for demonstration
data = {
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Houston'],
'Lat': [40.7128, 37.7749, 34.0522, 41.8781, 29.7604],
'Lon': [-74.0060, -122.4194, -118.2437, -87.6298, -95.3698],
'Population': [8175133, 870887, 3971883, 2716000, 2328000]
}
# Create a map
fig = px.scatter_geo(data, lat='Lat', lon='Lon', text='City', size='Population',
projection='natural earth', title='Population of Cities')
fig.update_traces(textposition='top center')

ISE,SIET18
Data Visualization with Python(BCS358D) 2024-2025

fig.show()

OUTPUT:

ISE,SIET19

You might also like