0% found this document useful (0 votes)
5 views45 pages

Final Manual BCS358D

The document outlines a laboratory course on Data Visualization with Python (BCS358D) for the III Semester CSE (IoT & Cyber Security) at Bangalore Institute of Technology for the academic year 2024-25. It details course prerequisites, learning objectives, outcomes, and a list of experiments that students will perform, including using libraries like Matplotlib, Seaborn, Bokeh, and Plotly. Additionally, it includes instructions for practical examinations and guidelines for students to follow during lab sessions.

Uploaded by

karanmahanta881
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)
5 views45 pages

Final Manual BCS358D

The document outlines a laboratory course on Data Visualization with Python (BCS358D) for the III Semester CSE (IoT & Cyber Security) at Bangalore Institute of Technology for the academic year 2024-25. It details course prerequisites, learning objectives, outcomes, and a list of experiments that students will perform, including using libraries like Matplotlib, Seaborn, Bokeh, and Plotly. Additionally, it includes instructions for practical examinations and guidelines for students to follow during lab sessions.

Uploaded by

karanmahanta881
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/ 45

BANGALORE INSTITUTE OF TECHNOLOGY

K.R. ROAD, V.V PURAM, BANGALORE - 560 004

(AFFILIATED TO VTU, BELAGAVI)

Department of CSE(IoT & Cyber Security including Blockchain Technology)


COURSE CODE: BCS358D

DATA VISUALIZATION WITH PYTHON LABORATORY

As per Choice Based Credit System Scheme (CBCS)

FOR III SEMESTER CSE(ICB) AS PRESCRIBED BY VTU

Academic Year 2024-25

Prepared By:
Nagabushan P
Asst Professor
Dept. of CSE(ICB), BIT
Bangalore Institute of Technology
K. R. Road, V.V. Pura, Bengaluru 560004

Department of CSE(IoT & Cyber Security including Blockchain Technology)


DATA VISUALIZATION WITH PYTHON LABORATORY
(BCS358D)
PRE-REQUISITES:
Python programming concepts.

COURSE LEARNING OBJECTIVES (CLO)


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: Implement of Matplotlib for drawing different Plots.
CLO 4: Demonstrate working with Seaborn, Bokeh.
CLO 5: Working with Plotly for 3D, Time Series and Maps.
COURSE OUTCOMES (CO)
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 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

Subject Code: CIE Marks: 50


BCS358D Hours/Week: Exam Hours:
0:0:2:0 03
Total Hours: 24
List of Programs

Sl. No. Name of Experiment ( Part- A )


a) Write a python program to find the best of two test average marks out of three test’s
marks accepted from the user.
1.
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.
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
2. error message if the condition for input value is not followed.
b) Develop a python 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 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:
3. 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
a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib..
4.
b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.

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


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

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


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

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.

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

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


10. b) Write a Python program for creating Maps using Plotly Libraries.
DATA VISUALIZATION WITH PYTHON LABORATORY

Subject Code: BCS358D CIE Marks: 50


Hours/Week: 0:0:2:0 Total Hours: 24
Lesson Planning / Schedule of Experiments

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:

1. All laboratory experiments are to be included for 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

1. Students should come with thorough preparation for the experiment to be


conducted.

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.

3. Practical record should be neatly maintained.


4. They should obtain the signatures of the staff in-charge in the observation book
after completing each experiment.

5. Theory regarding each experiment should be written in the practical record


before procedure in your own words.
6. Ask lab technician for assistance if you have any problem.
7. Save your class work, assignments in system.
8. Do not download or install software without the assistance of the laboratory
technician.
9. Do not alter the configuration of the system.
10. Turn off the systems after use.
BCS358D DATA VISUALIZATION WITH PYHTHON
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.
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.")

# Input three test scores for a single student


test_scores = []

for i in range(3):
test_scores.append(get_valid_test_score())

# Sort the test scores in descending order


test_scores.sort(reverse=True)

# Calculate the average of the best two test scores


best_two_averages = sum(test_scores[:2]) / 2

# Output the result


print("The average of the best two test scores is: {best_two_averages:.2f}")
BCS358D DATA VISUALIZATION WITH PYHTHON
OUTPUT:

1. Enter a test score: 98


Enter a test score: 65
Enter a test score: 85
The average of the best two test scores is: 91.50

2. Enter a test score: 52


Enter a test score: 52
Enter a test score: 48
The average of the best two test scores is: 52.00

3. Enter a test score: -2


Please enter a valid test score between 0 and 100.
BCS358D DATA VISUALIZATION WITH PYHTHON
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.

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:

1. Enter a number: 818


818 is a palindrome.
Digit 1 appears 1 times in the number.
Digit 8 appears 2 times in the number.

2. Enter a number: 123


123 is not a palindrome.
Digit 1 appears 1 times in the number.
Digit 2 appears 1 times in the number.
Digit 3 appears 1 times in the number.

3. Enter a number: - 125


Please enter anon-negative number.
BCS358D DATA VISUALIZATION WITH PYHTHON
Palindrome Program for strings

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)

for i in range(length // 2):


if s[i].isalnum() and s[length - i - 1].isalnum():
if s[i].lower() != s[length - i - 1].lower():
return False
elif not s[i].isalnum():
while nots[i].isalnum():
i += 1
elif not s[length - i - 1].isalnum():
while nots[length-i- 1].isalnum():
length -= 1
return True

# Input string from the user


string = input("Enter a string: ")
if is_palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")

OUTPUT:

1. Enter a string: rar


'rar' is a palindrome.

2. Enter a string: ram


'ram' is not a palindrome.
BCS358D DATA VISUALIZATION WITH PYHTHON
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 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

x = int(input("Enter a Binary number "))


result = BinToDec(x)
if result:
print("The Decimal equivalent of {0} is {1}".format(x, result))
y = int(input("Enter a Octal number "))

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:

Enter a Binary number 1111


The Decimal equivalent of 1111 is 15
Enter a Octal number 146523
CD53
The Hexa Decimal equivalent of 146523 is CD53
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-3

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:

Enter a sentence Rama went to Devaraja market to pick 2 kgs of vegetable


There are 11 words in the sentence
There are 1 digits, 2 upper case characters and 42 lower case characters in the sentence
BCS358D DATA VISUALIZATION WITH PYHTHON
3b) Write a Python program to find the string similarity between two given strings.

x = input("Enter first String")


y = input("Enter second String")
x = x.strip()
y = y.strip()
sim=0
if len(x)>len(y):
xx = x
yy = y
else:
xx = y
yy = x
j=0
for i in yy:
if i==xx[j]:
sim+=1
else:
pass
j+=1
similarity = (sim/len(xx))
print("The similarity between the two given strings is", similarity)

OUTPUT:

1. Enter first String Python Exercises


Enter second String Python Exercises
The similarity between the two given strings is 1.0

2. Enter first String Python Lab


Enter second String Python Laboratory
The similarity between the two given strings is 0.5882352941176471
BCS358D DATA VISUALIZATION WITH PYHTHON
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.
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.

Dataset (Cars_ Barplot.csv)


Car Sales
Audi 419
BMW 263
Mercedes 330
Honda 760

import matplotlib.pyplot asplt


import pandas aspd
# Initialize the lists for X and Y
data = pd.read_csv("Cars_Barplot.csv")
df = pd.DataFrame(data)
X = list(df.iloc[:, 0])
Y = list(df.iloc[:, 1])
# Plot the data using bar() method
plt.bar(X, Y, color='g')
plt.title("Used Car Sales")
plt.xlabel("Car")
plt.ylabel("Number Sold")
# Show the plot
plt.show()

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR

import matplotlib.pyplot asplt


# Data for the bar plot
categories=['CategoryA','CategoryB','CategoryC','CategoryD']
values = [10, 25, 15, 30]
# Create a bar plot
plt.bar(categories, values)
#Addlabelsandatitle
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')
# Display the plot
plt.show()

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
4b) Write a Python program to demonstrate how to draw a Scatter Plot using Matplotlib.

Dataset (Cars.csv)

I Model Price Age Mfg_Month Mfg_ KM Fuel_ HP Met_ Auto cc Doors


d Year Type Color matic
1 TOY 13500 23 10 2002 46986 Diesel 90 1 0 2000 3
OTA
Coroll
a 2.0
D4D
HATC
HB
TERR
A 2/3-
Doors
2 TOY 13750 23 10 2002 72937 Diesel 90 1 0 2000 3
OTA
Coroll
a 2.0
D4D
HATC
HB
TERR
A 2/3-
Doors
3 ?TOY 13950 24 9 2002 41711 Diesel 90 1 0 2000 3
OTAC
orolla
2.0
D4D
HATC
HB
TERR
A 2/3-
Doors
4 TOY 14950 26 7 2002 48000 Diesel 90 0 0 2000 3
OTA
Coroll
a 2.0
D4D
HATC
HB
TERR
A 2/3-
Doors
5 TOY 13750 30 3 2002 38500 Diesel 90 0 0 2000 3
OTA
Coroll
a 2.0
D4D
HATC
HB
SOL
2/3-
Doors
BCS358D DATA VISUALIZATION WITH PYHTHON
# import the necessary libraries
import pandas aspd
import numpy asnp
import matplotlib.pyplot asplt
# Importing data.
cars_data = pd.read_csv("Cars.csv")
# Create scatter plot using two variables, Age and Price.
plt.scatter(cars_data['Age'],cars_data['Price'],c='blue')
# To set the title
plt.title('Scatter plot of Price vs Age of the Cars')
# To set the x andy axis labels.
plt.xlabel('Age (months)')
plt.ylabel('Price (Euros)')
# To show the scatter plot
plt.show()

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
OR

import matplotlib.pyplot asplt


# Data for the scatter plot
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 17, 20]
# Create a scatter plot
plt.scatter(x, y, marker='o', color='blue', label='Data Points')
# Add labels and a title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
# Add a legend
plt.legend()
# Display the plot
plt.show()

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-5

5a) Write a Python program to demonstrate how to draw a Histogram using Matplotlib

# import the necessary libraries

# Pandas library for data frames

import pandas aspd

# numpy library to do numerical operations

import numpy asnp

import matplotlib.pyplot asplt

cars_data = pd.read_csv("cars.csv")

plt.title('Histogram for distance travelled in KiloMeter')

plt.hist(cars_data ['KM'], color='green', edgecolor='white', bins=5)

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

import matplotlib.pyplot asplt

import pandas aspd

# Creating dataset

cars_data = pd.read_csv("Cars_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()

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

import matplotlib.pyplot asplt


def linear_plot():
# Sample data
x = [1, 2, 3, 4, 5]
y = [3, 7, 9, 11, 14]
# Plotting the data
plt.plot(x, y, label='Linear Function: y = 2x')
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Linear Plot Example')
plt.legend()
plt.show()
# Call the function to generate the plot
linear_plot()

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

import matplotlib.pyplot asplt


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')
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Formatted Linear Plot Example')
plt.legend()
plt.grid(True) # Add a grid for better readability
plt.show()
# Call the function to generate the formatted linear plot
formatted_linear_plot()

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.

import seaborn as sns


import matplotlib.pyplot asplt
# Load a sample dataset
tips = sns.load_dataset("tips")
# Set the aesthetic style of the plot
sns.set(style="whitegrid")
# Create a scatter plot using Seaborn
sns.scatterplot(x="total_bill", y="tip", style="time", size="size", data=tips)
# Customize the plot further using Seaborn aesthetic functions
sns.despine() # Remove the top and right spines from the plot
# Set custom labels and title
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")
plt.title("Scatter Plot of Total Bill vs Tip")
# Show the plot
plt.show()

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-8

8a) 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]
# 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='Y-axis')
# 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:
BCS358D DATA VISUALIZATION WITH PYHTHON

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

# Import the necessary libraries


from bokeh.plotting import figure, show

# Create a line plot


x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
line = figure(title="Line Plot", x_axis_label="x", y_axis_label="y")
line.line(x, y, line_width=2)

# Create a bar plot


x = ["a", "b", "c", "d", "e"]
y = [1, 2, 3, 4, 5]
bar = figure(title="Bar Plot", x_range=x)
bar.vbar(x=x, top=y, legend_label="values", width=0.5, bottom=0)

# Create a pie chart


data = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
pie = figure(title="Pie Chart")
pie.wedge(x=1, y=1, radius=0.5, start_angle=0.5, end_angle=6.28, line_color="white", fill_color="blue",
legend_label="values")

# Show the plots


show(line)
show(bar)
show(pie)

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
BCS358D DATA VISUALIZATION WITH PYHTHON

PROGRAM-9

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

# Import necessary libraries


import plotly.graph_objects as go
import numpy as npx = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
z = np.random.randn(100, 100)
fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z, mode='markers')])
fig.update_layout(title='3D Scatter Plot', scene=dict(xaxis_title='X Axis', yaxis_title='Y Axis', zaxis_title='Z
Axis'))
fig.show()

OUTPUT:
BCS358D DATA VISUALIZATION WITH PYHTHON
PROGRAM-10

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

import plotly.graph_objects as godata = [


{'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:
BCS358D DATA VISUALIZATION WITH PYHTHON

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

import plotly.express aspx


# 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 amap
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:
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?

The following are the benefits of using Python language:

Object-Oriented Language, High-Level Language, Dynamically Typed language, Extensive support


Libraries, Presence of third-party modules, Open source and community development, Portable and
Interactive, Portable across Operating systems.
Is Python a compiled language or an interpreted language?

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.

Python provides various web frameworks to develop web applications.

The popular python web frameworks are Django, Pyramid, Flask.

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

What is the difference between / and // in Python?


// represents floor division whereas / represents precise division. 5//2 = 2 5/2 = 2.5
Is indentation is required in Python?
Yes, indentation is required in Python. A Python interpreter can be informed that a group of
statements belongs to a specific block of code by using Python indentation. Indentations make the code
easy to read for developers in all programming languages but in Python, it is very important to indent the
code in a specific order.

What is Scope in Python?


The location where we can find a variable and also access it if required is called the scope of a variable.
Python Local variable: Local variables are those that are initialized within a function and are uniqueto
that function. It cannot be accessed outside of the function.
Python Global variables: Global variables are the ones that are defined and declared outside any
function and are not specified to any function.
Module-level scope: It refers to the global objects of the current module accessible in the program.
Outermost scope: It refers to any built-in names that the program can call. The name referenced is
located last among the objects in this scope.

Python documentation strings(or docstrings) provide a convenient way of associating


documentation with Python modules, functions, classes, and methods. Declaring Docstrings: The docstrings
are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method, or
function declaration. All functions should have a docstring. Accessing Docstrings: The docstrings can be
accessed using the doc method of the object or using the help function.

What is slicing in Python?


Python Slicing is a string operation for extracting apart of the string, or some part of a list. With this
operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns
a new list from the existing list.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy