RV Institute of Technology & Management®
Rashtreeya Sikshana Samithi Trust
RV Institute of Technology and Management®
(Affiliated to VTU, Belagavi)
JP Nagar, Bengaluru - 560076
Department of Computer /Information Science and Engineering
Course Name: Data Visualization with Python
Course Code: BCS358D
III Semester 2022 Scheme
Prepared By:
Dr. Surbhi Agrawal
Associate Professor,
Department of Computer Science and Engineering
RVITM, Bengaluru – 560076
Email: [Link]@[Link]
RV Institute of Technology & Management®
Q1.
a. Write a python program to find the best of two test average marks out of
three test’s marks accepted from the user.
Python Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
m1 = int(input("Enter marks for test1 : "))
m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))
best_of_two = sorted([m1, m2, m3], reverse=True)[:2]
average_best_of_two = sum(best_of_two)/2
print("Average of best two test marks out of three test’s marks is",
average_best_of_two);
Output:
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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
RV Institute of Technology & Management®
from collections import Counter
value = input("Enter a value : ")
if value == value[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
counted_dict = Counter(value)
for key in sorted(counted_dict.keys()):
print(f'{key} appears {counted_dict[key]} times');
"""
#Alternate way to count appearances
for i in range(10):
if [Link](str(i)) > 0:
print(f'{str(i)} appears {[Link](str(i))} times')
"""
Output : 1
Output2:
Q2. 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.
Python Code:
#!/usr/bin/env python3
RV Institute of Technology & Management®
# -*- coding: utf-8 -*-
def fn(n):
if n <= 2:
return n - 1
else:
return fn(n-1) + fn(n-2)
try:
num = int(input("Enter a number : "))
if num > 0:
print(f' fn({num}) = {fn(num)}')
else:
print("Input should be greater than 0")
except ValueError:
print("Try with numeric value")
Ouput:
b) Develop a python program to convert binary to decimal, octal to hexadecimal
using functions.
Python Code
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
def bin2Dec(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 2**i
RV Institute of Technology & Management®
i += 1
return dec
def oct2Hex(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 8**i
i += 1
list=[]
while dec != 0:
[Link](dec%16)
dec = dec // 16
nl=[]
for elem in list[::-1]:
if elem <= 9:
[Link](str(elem))
else:
[Link](chr(ord('A') + (elem -10)))
hex = "".join(nl)
return hex
base = 2
num1 = input("Enter a binary number : ")
# print(bin2Dec(num1))
print(int(num1, base))
"""
#A better implementation
def bin2Dec(val):
return int(val, 2)
RV Institute of Technology & Management®
def oct2Hex(val):
return int(val, 8)
try:
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
except ValueError:
print("Invalid literal in input with base 2")
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.
Python Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
sentence = input("Enter a sentence : ")
wordList = [Link]().split(" ")
print(f'This sentence has {len(wordList)} words', end='\n\n')
digit_count = uppercase_count = lowercase_count = 0
RV Institute of Technology & Management®
for character in sentence:
if character in [Link]:
digit_count += 1
elif character in string.ascii_uppercase:
uppercase_count += 1
elif character in string.ascii_lowercase:
lowercase_count += 1
print(f'This sentence has {digit_count} digits',
f' {uppercase_count} upper case letters',
f' {lowercase_count} lower case letters', sep='\n')
Output:
b) Write a Python program to find the string similarity between two given strings
Python Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
str1 = input("Enter String 1 \n").lower()
str2 = input("Enter String 2 \n").lower()
# if len(str2) < len(str1):
# short = len(str2)
# long = len(str1)
# else:
# short = len(str1)
# long = len(str2)
string_1_length = len(str1)
string_2_length = len(str2)
RV Institute of Technology & Management®
short_string_length, long_string_length = min(string_1_length, string_2_length),
max(string_1_length, string_2_length)
match_count = 0
for i in range(short_string_length):
if str1[i] == str2[i]:
match_count += 1
print("Similarity between two said strings:")
print(match_count/long_string_length)
"""
# An alternative solution to the same problem using Python libraries
from difflib import SequenceMatcher
str1 = input("Enter String 1 : ")
str2 = input("Enter String 2 : ")
sim = SequenceMatcher(None, str1, str2).ratio()
print("Similarity between strings \"" + str1 + "\" and \"" + str2 + "\" is : ",sim)
Output:
Q4. a) Write a Python program to Demonstrate how to Draw a Bar Plot using
Matplotlib.
Python Code:
import [Link] as plt
RV Institute of Technology & Management®
# Sample data for demonstration
categories = ['0-10', '10-20', '20-30', '30-40', '40-50']
values = [55, 48, 25, 68, 90]
# Create a bar plot
[Link](categories, values, color='skyblue')
# Add labels and title
[Link]('Overs')
[Link]('Runs')
[Link]('Bar Plot Showing Runs scored in an ODI Match')
# Display the plot
[Link]()
Output:
b) Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.
Python Code:
import [Link] as plt
RV Institute of Technology & Management®
import numpy as np
# BRICS nations data (hypothetical)
countries = ['Brazil', 'Russia', 'India', 'China', 'South Africa']
population = [213993437, 145912025, 1393409038, 1444216107, 61608912] #
Population in 2021
per_capita_income = [9600, 11600, 2300, 11000, 6500] # Per capita income in
USD
# Scale the population for circle size
circle_size = [pop / 1000000 for pop in population] # Scaling down for better
visualization
# Assign different colors based on index
colors = [Link](len(countries))
# Create a scatter plot with varying circle sizes and colors
scatter = [Link](population, per_capita_income, s=circle_size, c=colors,
cmap='viridis', alpha=0.7, label='BRICS Nations')
# Annotate each point with the country name
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, label='Index')
# Add labels and title
[Link]('Population')
[Link]('Per Capita Income (USD)')
[Link]('Population vs Per Capita Income of BRICS Nations')
# Display the plot
[Link]()
RV Institute of Technology & Management®
Q5. a) Write a Python program to Demonstrate how to Draw a Histogram Plot
using Matplotlib.
Python Code:
import [Link] as plt
import numpy as np
# Generate random student scores (example data)
[Link](42)
student_scores = [Link](loc=70, scale=15, size=100)
# Create a histogram plot
[Link](student_scores, bins=20, color='skyblue', edgecolor='black')
# Add labels and title
[Link]('Student Scores')
[Link]('Frequency')
[Link]('Distribution of Student Scores')
# Display the plot
[Link]()
RV Institute of Technology & Management®
Output :
b) Write a Python program to Demonstrate how to Draw a Pie Chart using
Matplotlib.
Python Code:
import [Link] as plt
#Number of FIFA World Cup wins for different countries
countries = ['Brazil', 'Germany', 'Italy', 'Argentina', 'Uruguay', 'France', 'England',
'Spain']
wins = [5, 4, 4, 3, 2, 2, 1, 1] # Replace with actual data
# Colors for each country
colors = ['yellow', 'magenta', 'green', 'blue', 'lightblue', 'blue', '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)
# Add title
[Link]('FIFA World Cup Wins by Country')
# Display the plot
RV Institute of Technology & Management®
[Link]('equal') # Equal aspect ratio ensures that the pie chart is circular.
[Link]()
Output:
Q6. a) Write a Python program to illustrate Linear Plotting using Matplotlib.
Python Code:
import [Link] as plt
# Hypothetical data: Run rate in an T20 cricket match
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]
# Create a linear plot
[Link](overs, runs_scored)
# Add labels and title
[Link]('Overs')
[Link]('Runs scored')
[Link]('Run scoring in an T20 Cricket Match')
# Display the plot
[Link](True)
RV Institute of Technology & Management®
[Link]()
Output:
b) Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.
Python Code:
import [Link] as plt
# Hypothetical data: Run rate in an T20 cricket match
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]
# Create a linear plot
[Link](overs, runs_scored, marker='X', linestyle='dashed',color='red',
linewidth=2, markerfacecolor='blue', markersize=8)
# Add labels and title
[Link]('Overs', color = 'green')
[Link]('Runs scored')
RV Institute of Technology & Management®
[Link]('Run scoring in an T20 Cricket Match')
# Display the plot
[Link](True)
[Link]()
Output:
Q7. Write a Python program which explains uses of customizing seaborn plots
with Aesthetic functions.
Python Code:
import numpy as np
import [Link] as plt
import seaborn as sns
def sinplot(n=10):
x = [Link](0, 14, 100)
for i in range(1, n + 1):
[Link](x, [Link](x + i * .5) * (n + 2 - i))
RV Institute of Technology & Management®
[Link]() # to set the theme
#sns.set_context("talk")
sns.set_context("notebook", font_scale=1.5, rc={"[Link]": 2.5})
sinplot()
[Link]('Seaborn plots with Aesthetic functions')
[Link]()
Output :
Q8. Write a Python program to explain working with bokeh line graph using
Annotations and Legends.
Write a Python program for plotting different types of plots using Bokeh.
Python Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
RV Institute of Technology & Management®
import numpy as np
from [Link] import gridplot
from [Link] import figure, show
x = [Link](0, 4*[Link], 100)
y = [Link](x)
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p1 = figure(title="Example 1", tools=TOOLS, width=400, height=400)
[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'
p2 = figure(title="Example 2", tools=TOOLS, width=400, height=400)
[Link](x, y, legend_label="sin(x)")
[Link](x, y, legend_label="sin(x)")
[Link](x, 2*y, legend_label="2*sin(x)",
line_dash=(4, 4), line_color="orange", line_width=2)
[Link](x, 3*y, legend_label="3*sin(x)", fill_color=None, line_color="green")
[Link](x, 3*y, legend_label="3*sin(x)", line_color="green")
[Link] = 'Lines'
show(gridplot([p1, p2], ncols=2))
Output:
RV Institute of Technology & Management®
Q9. Write a Python program to draw 3D Plots using Plotly Libraries
Python 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))')
RV Institute of Technology & Management®
# Display the 3D surface plot
[Link]()
Output:
Q10. a) Write a Python program to draw Time Series using Plotly Libraries.
Python Code: Dataset to be downloaded here- [Link]
content/uploads/2023/10/CUR_DLR_INR.csv
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import [Link] as px
dollar_conv = pd.read_csv('CUR_DLR_INR.csv')
fig = [Link](dollar_conv, x='DATE', y='RATE', title='Dollar vs Rupee')
[Link]()
OUTPUT:
RV Institute of Technology & Management®
b) Write a Python program for creating Maps using Plotly Libraries.
Python Code: Download Gapminder dataset Example 1
import [Link] as px
import pandas as pd
# Import data from GitHub
data =
pd.read_csv('[Link]
er_with_codes.csv')
# Create basic choropleth map
fig = [Link](data, locations='iso_alpha', color='gdpPercap',
hover_name='country',
projection='natural earth', title='GDP per Capita by Country')
[Link]()
Output:
RV Institute of Technology & Management®
RV Institute of Technology & Management®
Viva Questions
1. What are some important features of a good data visualization?
2. What is a scatter plot? For what type of data is scatter plot usually used for?
3. What features might be visible in scatterplots?
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.
6. What type of data is box-plots usually used for? Why?
7. When analyzing a histogram, what are some of the features to look for?
8. What type of data is histograms usually used 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?
11. How do you determine the color palette in your plots?
12. What is the difference between [Link]() and [Link]() in Matplotlib?
13. How can you create a histogram in Matplotlib?
14. How can you add a legend to a plot in Matplotlib?
15. What is the purpose of the [Link]() function in Matplotlib?
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?
18. How can you add text to a plot in Matplotlib?
19. What is the difference between a bar plot and a histogram in Matplotlib?
20. What is the purpose of the [Link]() function in Matplotlib?
21. How can you create a pie chart in Matplotlib?
22. How can you create a heat map in Matplotlib?
23. What is Seaborn?
24. Does Seaborn need Matplotlib?
25. What is CMAP in Seaborn?
26. How do you plot a histogram in Seaborn?
27. How do I make all of the lines in [Link] black?
28. How to change the legend font size of FacetGrid plot in Seaborn?
29. What is Plotly?
RV Institute of Technology & Management®
30. What are some of the main features offered by Plotly?
31. When should we use Plotly instead of Seaborn?
32. What’s the significance of x0, y0, dx, dy, angle, color, alpha, align, and font size parameters
in Plotly?
33. What types of plots can be created using Plotly?
34. What is the difference between express and graph_objects in Plotly?
35. What is the difference between Plotly and Matplotlib?