Final_dvp_manual (1)
Final_dvp_manual (1)
Semester: 3
Scheme: 2022
Prepared By:
Mrs. Rachana M S
Assistant Professor,
Department of Computer Science and Engineering
Email: [email protected]
1a) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
print("Average of best two test marks out of three test’s marks is",
average_best_of_two)
Output:
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.
Output : 1
Output2:
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n - 1) + fn(n - 2)
Output
import sys
def bin2dec(val):
rev = val[::-1]
# print(rev)
i=0
dec = 0
for dig in rev:
dec = dec + int(dig) * 2 ** i
i=i+1
return dec
else:
nl.append(chr(ord('A') + (elem - 10)))
hex = "".join(nl)
III-Semester, Data Visualization using Python (BCS358D) P a g e 4 | 22
RV Institute of Technology and Management®
return hex
try:
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
except ValueError:
print("Invalid literal in input with base 8")
Output :
Q3. Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters and lowercase letters.
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
print ("No of Words: ", words)
print ("No of Digits: ", digits)
print ("No of Uppercase letters: ", upper)
print ("No of Lowercase letters: ", lower)
Output:
3b) Write a Python program to find the string similarity between two given
strings
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt / long)
or
# An alternative solution to the same problem using Python libraries
Output:
Data Visualization
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.
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
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 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.
4a) Write a Python program to demonstrate how to draw a Bar Plot using
Matplotlib.
Output
4b) Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.
# Add colorbar
plt.colorbar(scatter,
label='Index')
Output
Output
wins = [5, 4, 4, 3, 2, 2, 1, 1]
# Replace with actual data
# Add title
plt.title('FIFA World Cup Wins by Country')
Python Code:
Output
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.show()
Q7. Write a Python program which explains uses of customizing seaborn plots
with Aesthetic functions.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def sinplot(n=10):
x = np.linspace(0, 14, 100)
for i in range(1, n + 1):
plt.plot(x, np.sin(x + i * .5) * (n + 2 - i))
sns.set() # to set the theme
#sns.set_context("talk")
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sinplot()
plt.title('Seaborn plots with Aesthetic functions')
plt.show()
Output:
OR
Output:
Q8. a Write a Python program to explain working with bokeh line graph using
Annotations and Legends.
import numpy as np
from bokeh.layouts import gridplot
from bokeh.plotting import figure, show
x = np.linspace(0, 4*np.pi,
100) y = np.sin(x)
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p2.circle(x, y, legend_label="sin(x)")
p2.line(x, y, legend_label="sin(x)")
p2.legend.title = 'Lines'
Output:
Q8.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
# Load the tips dataset
tips = pd.read_csv("tips.csv")
# 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)
import plotly.graph_objects as go
import pandas as pd
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')
Output:
Q10. a) Write a Python program to draw Time Series using Plotly Libraries.
import pandas as pd
import plotly.express as
px
dollar_conv = pd.read_csv('CUR_DLR_INR.csv')
Output:
import plotly.express as px
import pandas as pd
data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapmind
er_with_codes.csv')
fig.show()
Output:
Viva Questions
2. What is a scatter plot? For what type of data is scatter plot usually used for?
4. What type of plot would you use if you need to demonstrate “relationship” between
variables/parameters?
5. When will you use a histogram and when will you use a bar chart? Explain with an example.
7. When analyzing a histogram, what are some of the features to look for?
9. What is the difference between count histogram, relative frequency histogram, cumulative
frequency histogram and density histogram?
10. What are some advantages of using cleveland dot plot versus bar chart?
16. How can you set the font size of a plot in Matplotlib?
17. What is the difference between a scatter plot and a line plot in Matplotlib?
19. What is the difference between a bar plot and a histogram in Matplotlib?
28. How to change the legend font size of FacetGrid plot in Seaborn?
32. What’s the significance of x0, y0, dx, dy, angle, color, alpha, align, and font size parameters
in Plotly?