DVP Manual V2
DVP Manual V2
III SEM
BCS358D
Prepared By:
Dr. Girija J & Dr. Madhuri J
Dept. of CS&E
1
DVP Lab Manual
This laboratory course enables students to get practical experience in design, develop,
implement, analyze and evaluation/testing of
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.
On the completion of this laboratory course, the students will be able to:
CO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications
CO 2. Use Python programming constructs to develop programs for solving real-world problems
CO 3. Use Matplotlib for drawing different Plots
CO 4. Demonstrate working with Seaborn, Bokeh for visualization.
CO 5. Use Plotly for drawing Time Series and Maps.
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 3
BCS358D
CO2 3 3 3 3
CO3 3
CO4 3
CO5 3
PSO1 PSO2
CO1 2
BCS358D CO2 2 2
CO3 2
CO4 2
2
DVP Lab Manual
CO5 2
3
DVP Lab Manual
3. Sample Output:
Original string: Original string:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: 1.0 Similarity between two said strings: 0.96774193548
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.
Write a Python program to explain working with bokeh line graph using Annotations and
8. 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.
4
DVP Lab Manual
5
DVP Lab Manual
PROGRAM -1
1a) Write a Python program to find the best of two test average marks out of three test marks
accepted by the user.
OUTPUT
Enter marks for test1: 45
Enter marks for test2: 39
Enter marks for test3: 48
Average of best two test marks out of three test’s marks is 46.5
6
DVP Lab Manual
1b) 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.
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: 1234234
Not Palindrome
1 appears 1 times
2 appears 2 times
3 appears 2 times
4 appears 2 times
Enter a value: 12321
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 1 times
7
DVP Lab Manual
PROGRAM -2
2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program that accepts a value
for N (where N >0) as input and pass this value to the function. Display a suitable error
message if the condition for input value is not followed.
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")
OUTPUT:
Enter a number : 5
fn(5) = 3
Enter a number : -5
Error in input
8
DVP Lab Manual
2b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
def bin_to_dec():
bin=int(input("Enter a binary number : "))
dec=0
i=0
while bin!=0:
dec+=(bin%10)*(2**i)
i+=1
bin//=10
print("Decimal Equivalent is : ",dec)
def oct_to_hex():
oct=int(input("Enter an octal number : "))
dec=0
i=0
while oct!=0:
dec+=(oct%10)*(8**i)
i+=1
oct//=10
hex =""
while dec!=0:
rem=dec%16
if rem<10:
hex+=str(rem)
else:
hex+= chr(ord('A')+rem-10)
dec//=16
hex=hex[::-1]
print("Hexadecimal Equivalent is : ", hex)
9
DVP Lab Manual
PROGRAM -3
3a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters, and lowercase letters.
sentence = input("Enter a sentence: ")
words = digits = upper = lower = 0
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
elif c.isupper():
upper = upper + 1
elif c.islower():
lower = lower + 1
OUTPUT:
Enter a sentence: Rama went to Devaraja market to pick 2 kgs of vegetable
The result of split() on input sentence is :
['Rama', 'went', 'to', 'Devaraja', 'market', 'to', 'pick', '2', 'kgs', 'of', 'vegetable']
No of Words: 11
No of Digits: 1
No of Uppercase letters: 2
No of Lowercase letters: 42
10
DVP Lab Manual
3b) Write a Python program to find the string similarity between two given strings.
str1 = input("Enter String 1 \n")
str2 = input("Enter String 2 \n")
OUTPUT:
Enter String 1
Python Exercises
Enter String 2
Python Exercises
Similarity between two said strings:
1.0
Enter String 1
Python Exercises
Enter String 2
Python Exercise
Similarity between two said strings: 0.9375
11
DVP Lab Manual
Matplotlib
Matplotlib is a popular Python library for creating static, animated, and interactive visualizations
in a variety of formats. It is widely used for producing high-quality plots and charts in scientific
computing, data analysis, and machine learning. Matplotlib provides a range of functions for
creating different types of plots, including line plots, scatter plots, bar plots, histograms, and more.
Different visualizations plots are as follows:
Scatter plots: Scatter plots are particularly useful when exploring the relationship between two
continuous variables. They excel at revealing patterns, trends, and correlations between data
points. These visualizations are adept at identifying outliers, showcasing them as points deviating
from the main cluster. By providing a clear picture of the distribution of data points along two
axes, scatter plots aid in understanding the spread and density of values. Moreover, they are
valuable for comparing different datasets, recognizing similarities or differences.
Histogram: A histogram is a graphical representation of the distribution of a dataset, typically
used for continuous or discrete data. It provides a way to visualize the frequency or count of data
points within specific intervals or bins. In a histogram, the data is divided into contiguous, non-
overlapping intervals, and the height of each bar in the chart represents the frequency or count of
data points falling within that interval.
To create a histogram, you divide the range of the data into bins or intervals and then count
the number of data points that fall into each bin. The resulting bar chart, with the bars representing
these counts, provides a visual summary of the data's distribution.
Bar chart: A bar chart is a graphical representation of data in which rectangular bars are used to
represent the values of different categories. Each bar's length is proportional to the value it
represents. Bar charts are effective for comparing discrete categories or groups and are particularly
useful for showing the distribution of categorical data.
Pie chart: Pie charts are a type of data visualization that is commonly used to represent the
proportions of different parts of a whole. The primary purpose of a pie chart is to show the
relationship of parts to a whole and to illustrate how each part contributes to the total.
Seaborn
Seaborn is a statistical data visualization library built on top of Matplotlib in Python. It provides
an interface for creating informative and attractive statistical graphics. Seaborn comes with several
built-in themes and color palettes to make it easy to create aesthetically pleasing visualizations. It
is particularly useful for exploring complex datasets and understanding relationships between
variables.
Bokeh
Bokeh is a Python interactive visualization library that targets modern web browsers for
presentation. It allows you to create interactive, web-ready visualizations in Python. Bokeh
12
DVP Lab Manual
generates HTML and JavaScript code that can be embedded into web pages. This allows you to
create interactive visualizations that can be easily shared on the web.
Plotly
Plotly is a versatile Python library for creating interactive and publication-quality plots and
dashboards. It supports a wide range of chart types. Plotly excels at creating interactive plots. Users
can zoom, pan, hover over data points for additional information, and perform other interactive
actions directly within the plot. Its ability to create web-based dashboards makes it a powerful tool
for building data-driven applications.
Dataset used
1. Cars.csv
Id Model Price Age Mfg_Month Mfg_Year KM Fuel_Type HP Met_Color Automatic cc Doors
TOYOTA
Corolla 2.0 D4D
1 HATCHB 13500 23 10 2002 46986 Diesel 90 1 0 2000 3
TERRA 2/3-
Doors
TOYOTA
Corolla 2.0 D4D
2 HATCHB 13750 23 10 2002 72937 Diesel 90 1 0 2000 3
TERRA 2/3-
Doors
?TOYOTA
Corolla 2.0 D4D
3 HATCHB 13950 24 9 2002 41711 Diesel 90 1 0 2000 3
TERRA 2/3-
Doors
TOYOTA
Corolla 2.0 D4D
4 HATCHB 14950 26 7 2002 48000 Diesel 90 0 0 2000 3
TERRA 2/3-
Doors
TOYOTA
Corolla 2.0 D4D
5 13750 30 3 2002 38500 Diesel 90 0 0 2000 3
HATCHB SOL
2/3-Doors
13
DVP Lab Manual
2. Cars_BarPlot
Car Sales
Audi 419
BMW 263
Mercedes 330
Honda 760
3. tips.csv
4. Rainfall_data
Specific Relative
Year Month Day Humidity Humidity Temperature Precipitation
2000 1 1 8.06 48.25 23.93 0
2000 2 1 8.73 50.81 25.83 0.11
2000 3 1 8.48 42.88 26.68 0.01
2000 4 1 13.79 55.69 22.49 0.02
2000 5 1 17.4 70.88 19.07 271.14
14
DVP Lab Manual
4a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib
15
DVP Lab Manual
4. b) Write a Python program to Demonstrate how to draw a Scatter Plot using Matplotlib
# import the necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Importing data.
cars_data = pd.read_csv("Toyota.csv")
16
DVP Lab Manual
import numpy as np
import matplotlib.pyplot as plt
cars_data = pd.read_csv("cars.csv")
plt.title('Histogram for distance travelled in KiloMeter')
17
DVP Lab Manual
# Import libraries
import matplotlib.pyplot as plt
import pandas as pd
# Creating dataset
cars_data = pd.read_csv("Car_BarPlot.csv")
cars = cars_data["Car"]
data = cars_data["Sales"]
# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)
# show plot
plt.show()
18
DVP Lab Manual
19
DVP Lab Manual
6b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib
import matplotlib.pyplot as plt
def formatted_linear_plot():
# Sample data
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.legend()
plt.grid(True) # Add a grid for better readability
plt.show()
Output
20
DVP Lab Manual
7a) Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.
21
DVP Lab Manual
Output
22
DVP Lab Manual
8 a) Write a Python program to explain working with bokeh line graph using Annotations
and Legends.
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]
# Create a figure
p = figure(title="Bokeh Line Graph with Annotations", x_axis_label='X-axis', y_axis_label='Y-
axis')
# 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"
23
DVP Lab Manual
Output
24
DVP Lab Manual
8 b) Write a Python program for plotting different types of plots using Bokeh
import pandas as pd
import numpy as np
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import gridplot
# Histogram
hist, edges = np.histogram(tips['total_bill'], bins=8)
hist_plot = figure(title="Histogram of Total Bill", x_axis_label='Total Bill',
y_axis_label='Frequency')
hist_plot.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="purple",
line_color="white")
# Bar Plot
day_categories = tips['day'].unique()
average_total_bill = tips.groupby('day')['total_bill'].mean()
bar_plot = figure(title="Average Total Bill per Day", x_axis_label='Day', y_axis_label='Average
Total Bill', x_range=day_categories)
bar_plot.vbar(x=day_categories, top=average_total_bill, width=0.5, color="orange")
# Scatter Plot
scatter_plot = figure(title="Scatter Plot of Total Bill vs Tip", x_axis_label='Total Bill',
y_axis_label='Tip')
scatter_plot.scatter(x='total_bill', y='tip', size=8, color="green", alpha=0.6, source=tips)
25
DVP Lab Manual
Output
26
DVP Lab Manual
import plotly.graph_objects as go
import pandas as pd
scatter = go.Scatter3d(
x=tips['total_bill'],
y=tips['tip'],
z=tips['size'],
mode='markers',
marker=dict(size=8, color=tips['size'], colorscale='Viridis', opacity=0.8)
)
fig.add_trace(scatter)
# Set axis labels and title
fig.update_layout(scene=dict(xaxis_title='Total Bill', yaxis_title='Tip', zaxis_title='Size'))
fig.update_layout(title='3D Scatter Plot with Tips Dataset')
27
DVP Lab Manual
Output
28
DVP Lab Manual
10a). Write a Python program to draw Time Series using Plotly Libraries
import plotly.express as px
import pandas as pd
# Load the dataset (replace 'your_dataset.csv' with the actual file path)
data = pd.read_csv("Rainfall_data.csv")
Output
29
DVP Lab Manual
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')
fig.show()
Output
30