Final Manual BCS358D
Final Manual BCS358D
Prepared By:
Nagabushan P
Asst Professor
Dept. of CSE(ICB), BIT
Bangalore Institute of Technology
K. R. Road, V.V. Pura, Bengaluru 560004
CO1 2 3
CO2 2 3 2 3
BCS358D
CO3 2 3
CO4 2 3
CO5 2 3
PSO1 PSO2
CO1 1 2
BCS358D
CO2 2 2
CO3 2 2
CO4 2 2
CO5 1 2
DATA VISUALIZATION WITH PYTHON LABORATORY
7. a) 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 Annotations and
8. Legends.
a) Write a Python program for plotting different types of plots using Bokeh.
Sl. WEEK
Name of Experiment
No
1 Sample Programs Week1
2 a. To find the best of two test average marks out of three test’s Week2
marks.
b. To check whether a given number is palindrome or not and alsocount
the number of occurrences of each digit in the input
number.
3 a. Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python Week3
program which accepts a value for N (where N >0) as input and
pass this value to the function.
b. Program to convert binary to decimal, octal to hexadecimal
using functions
a) Write a Python program that accepts a sentence and find the number of Week4
words, digits, uppercase letters and lowercase letters. 03092022
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 Exercises
Similarity between two said strings: Similarity between two said
1.0 strings: 0.967741935483871
4 a. Demonstrate how to Draw a Bar Plot using Matplotlib Week5
b. Demonstrate how to Draw a Pie Chart using Matplotlib
5 a. Demonstrate how to Draw a Histogram Plot using Matplotlib. Week6
b. Demonstrate how to Draw a Pie Chart using Matplotlib.
6 LAB TEST - 1
Week7
a. Illustrate Linear Plotting using Matplotlib. Week8
7
b. Illustrate liner plotting with line formatting using Matplotlib.
8 a. Program which explains uses of customizing seaborn plots with Week9
Aesthetic functions.
9 Program to explain working with bokeh line graph using Annotations and Week10
Legends.
a. Program for plotting different types of plots using Bokeh.
10 Program to draw 3D Plots using Plotly Libraries. Week11
11 a. Python program to draw Time Series using Plotly Week12
Libraries.
b. Program for creating Maps using Plotly Libraries.
12 LAB TEST - 2 Week13
Conduction of Practical Examination:
2. Students are allowed to pick one experiment from Part A with lot.
3. Marks distribution:
Procedure (15%) + Execution (70%) + Viva (15%)
Part A: (15+70+15=100)
Final Exam Marks: /50 Marks (100 scaled down to 50)
4. Change of experiment is allowed only once and marks allotted to the write up part to be
made Zero.
Instructions to the Candidates
2. Students will not be permitted to attend the laboratory unless they bring the
practical record fully completed in all respects pertaining to the experiment
conducted in the previous class.
1a) Write a Python program to find the best of two test average marks out of three test marks
accepted by the user.
def get_valid_test_score():
while True:
try:
score = float(input("Enter a test score: "))
if 0 <= score <= 100:
return score
else:
print("Please enter a valid test score between 0 and 100.")
except ValueError:
print("Invalid input. Please enter a valid number.")
for i in range(3):
test_scores.append(get_valid_test_score())
def is_palindrome(number):
number_str = str(number)
return number_str == number_str[::- 1]
def count_digits(number):
digit_count = [0] * 10 # Initialize a list to count each digit from 0 to
9
while number >0:
digit = number % 10
# Get the last digit
digit_count[digit] += 1
# Increment the count for that digit
number //= 1
# Remove the last digit
return digit_count
try:
num = int(input("Enter a number: "))
if num <0:
print("Please enter anon-negative number.")
else:
if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
digit_count = count_digits(num)
for digit, count in enumerate(digit_count):
if count >0:
print(f"Digit {digit} appears {count} times in the number.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
BCS358D DATA VISUALIZATION WITH PYHTHON
OUTPUT:
def is_palindrome(s):
s = s.lower() # Convert to lowercase to make it case-insensitive
s = list(s) #Convert the string to a list
length = len(s)
OUTPUT:
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 messageif the
condition for input value is not followed.
def fn(n):
if n == 1:
return 0
elifn == 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:
1. Enter a number : 5
fn(5) = 3
2. Enter a number : -4
Error in input
BCS358D DATA VISUALIZATION WITH PYHTHON
2b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
defBinToDec(x):
dec = 0
i=0
while x>0:
r = x%10
ifr!=0 andr!=1:
print("Enter a valid Binary number")
return 0
else:
dec = dec + r*2**i
x = x // 10
i += 1
return dec
def OctaToHexa(n):
num = n
dec = 0
base = 1
temp = num
while temp:
r = temp % 10
temp = temp // 10
dec += r * base
base = base * 8
result = ' '
while dec != 0:
temp = 0
temp = dec % 16
if temp < 10:
result = str(temp) + result
else:
result = chr(temp + 55) + result
dec = dec // 16
return result
result = OctaToHexa(y)
BCS358D DATA VISUALIZATION WITH PYHTHON
print(result)
if result:
print("The Hexa Decimal equivalent of {0} is {1}".format(y, result))
OUTPUT:
3a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters, and lowercase letters.
x = input("Enter a sentence")
y=x
print("There are",len(x.split())," words in the sentence")
digits,upper,lower=0,0,0
for i in x:
if i.isdigit():
digits+=1
elifi.isupper():
upper+=1
elifi.islower():
lower+=1
print("There are {0} digits, {1} upper case characters and {2} lower case characters in the
sentence".format(digits,upper,lower))
OUTPUT:
OUTPUT:
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.
BCS358D DATA VISUALIZATION WITH PYHTHON
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 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.
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-4
4a) Write a Python program to demonstrate how to draw a Bar Plot using Matplotlib.
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
4b) Write a Python program to demonstrate how to draw a Scatter Plot using Matplotlib.
Dataset (Cars.csv)
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-5
5a) Write a Python program to demonstrate how to draw a Histogram using Matplotlib
cars_data = pd.read_csv("cars.csv")
plt.xlabel('Kilometer')
plt.ylabel('Frequency')
plt.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
import numpy asnp
# Sample data: Student grades
grades = [75, 82, 92, 88, 78, 90, 85, 95, 70, 87, 93, 79, 81, 86, 89, 94, 73, 84, 91, 77]
# Create a histogram
plt.figure(figsize=(8, 6))
plt.hist(grades, bins=[70, 75, 80, 85, 90, 95, 100], edgecolor='black', alpha=0.7, color='skyblue')
# Customize labels and title
plt.xlabel('Grades')
plt.ylabel('Frequency')
plt.title('Grade Distribution in a Class')
# Set the x-axis limits
plt.xlim(70,100)
# Display the plot
plt.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
5b) Write a Python program to demonstrate how to draw a Pie chart using Matplotlib
# Import libraries
# Creating dataset
cars_data = pd.read_csv("Cars_Barplot.csv")
cars = cars_data["Car"]
data = cars_data["Sales"]
# Creating plot
# show plot
plt.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
import matplotlib.pyplot asplt
# Data for the household budget pie chart
categories=['Housing','Utilities','Transportation','Food','Entertainment','Savings']
expenses = [30, 10, 15, 20, 10, 15]
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0','#ffb3e6']
explode = (0.1, 0.1, 0, 0, 0, 0)
# Create a pie chart
plt.pie(expenses, labels=categories, autopct='%1.1f%%', startangle=140, colors=colors,
explode=explode)
# Add a title
plt.title('Household Budget Expenses')
# Display the plot
plt.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-6
6a) Write a Python program to illustrate Linear Plotting using Matplotlib
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
import matplotlib.pyplot asplt
# Data for the linear plot
years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]
revenue = [50000, 60000, 65000, 75000, 80000, 90000, 100000, 110000]
# Create a linear plot
plt.plot(years,revenue, marker='o', color='green', linestyle='-', label='Annual Revenue')
# Add labels and a title
plt.xlabel('Year')
plt.ylabel('Revenue ($)')
plt.title('Company Annual Revenue Over the Years')
# Add a grid
plt.grid(True, linestyle='--', alpha=0.7)
# Add a legend
plt.legend()
# Display the plot
plt.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
6b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
import matplotlib.pyplot asplt
# Data for the linear plot
years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]
revenue = [50000, 60000, 65000, 75000, 80000, 90000, 100000, 110000]
# Create a linear plot with line formatting
plt.plot(years,revenue, marker='o', linestyle='-', color='green', label='Annual Revenue', linewidth=2,
markersize=8)
# Add labels and a title
plt.xlabel('Year')
plt.ylabel('Revenue ($)')
plt.title('Company Annual Revenue Over the Years')
# Add a grid
plt.grid(True, linestyle=':', alpha=0.7)
# Add a legend
plt.legend()
# Display the plot
plt.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-7
7a) Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-8
8a) Write a Python program to explain working with bokeh line graph using Annotations and
Legends.
OR
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.models.annotations import Title, Legend, LegendItem
from bokeh.io import output_notebook
# Sample data
x = [1, 2, 3, 4, 5]
y1 = [2, 5, 8, 6, 7]
y2 = [4, 6, 7, 5, 9]
# Create a Bokeh figure
p = figure(title="Line Graph with Annotations and Legends", x_axis_label="X-axis", y_axis_label="Y-
axis")
# Add data sources
source1=ColumnDataSource(data=dict(x=x,y=y1))
source2 = ColumnDataSource(data=dict(x=x, y=y2))
# Plot the first line
line1 = p.line('x', 'y', source=source1, line_width=2, line_color="blue", legend_label="Line 1")
# Plot the second line
line2 = p.line('x', 'y', source=source2, line_width=2, line_color="red", legend_label="Line 2")
# Add an annotation
annotation=Title(text="AnnotationExample",text_font_size="14px")
p.add_layout(annotation, 'above')
# Create a legend
legend=Legend(items=[LegendItem(label="Line1",renderers=[line1]),LegendItem(label="Line2",renderer
s=[line2])])
p.add_layout(legend, 'above')
# Show the plot
output_notebook()
show(p)
BCS358D DATA VISUALIZATION WITH PYHTHON
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
8b) Write a Python program for plotting different types of plots using Bokeh
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-9
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-10
10a). Write a Python program to draw Time Series using Plotly Libraries.
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR
import plotly.express aspx
import pandas aspd
# Load your dataset (ensure it has 'lat' and 'lng' columns for latitude and longitude)
data = {
"City": ["Bengaluru", "Mysuru", "Belagavi", "Kalburgi", "Davanagere", "New Delhi"],
"Lat": [12.9716, 12.2958, 15.8497, 17.3291, 14.4644, 28.6139],
"Lon": [77.5946, 76.6394, 74.5048, 77.2471, 75.9224, 77.2090]
}
df = pd.DataFrame(data)
# Create a scatter map plot
fig = px.scatter_geo(df, lat="Lat", lon="Lon", text="City",
title="Cities in India", projection="natural earth")
# Show the map
fig.show()
OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
VIVA QUESTIONS
What is Python?
1. Python is one of the most widely-used and popular programming languages, was developed by Guido
van Rossum and released first on February 20, 1991.
2. Python is a free and open-source language with a very simple and clean syntax which makes it easy
for developers to learn Python.
3. It supports object-oriented programming and is most commonly used to perform general-purpose
programming.
4. Python is used in several domains like Data Science, Machine Learning, Deep Learning, Artificial
Intelligence, Scientific Computing Scripting, Networking, Game Development Web Development, Web
Scraping, and various other domains, System Scripting, Software Development, and Complex
Mathematics.
What are the benefits of using Python language as a tool in the present scenario?
Python is a partially compiled language and partially interpreted language. ‘#’ is used to comment on
everything that comes after on the line.
Difference between a Mutable datatype and an Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc. Immutable data
types cannot be edited i.e., they cannot change at runtime. Eg – String, Tuple, etc.
What is a lambdafunction?
A lambda function is an anonymous function. This function can have any number of parameters but,can
have just one statement.
Pass means performing no operation or in other words, it is a placeholder in the compound statement,where
there should be a blank left and nothing has to be written there.
1. Python's standard library supports forE-mail processing, FTP, IMAP, and other Internet protocols.
2. Python's SciPy and NumPyhelp in scientific and computational application development.
3. Python's Tkinter library supports to create desktop-based GUI applications.
BCS358D DATA VISUALIZATION WITH PYHTHON
PIP is an acronym for Python Installer Package which provides a seamless interface to install various
Python modules. It is a command-line tool that can search for packages over the internet and install them
without any user interaction.