DV_Lab_Manual_BCS358D.docx[1]

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

CMR Institute of Technology, Bengaluru

Department of Computer Science and Technology


LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Lab Manual

an
M
b
La
Data Visualization with Python

on
th
Py
Semester III

ith
Course Code BCS358D

w
n
io
at
Teaching Hours/Week - 2
iz
al
su

CIE Marks 50
Vi
a
at
-D

SEE Marks 50
D
58

Credits 01
S3
BC
IT

Exam Hours 100


R
M

(Applicable for 3rd Sem CSE)


C

1 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Course Objectives (Defined by the university):

an
CLO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications

M
CLO 2. Using Python programming language to develop programs for solving real-world problems
CLO 3. Implementation of matplotlib for drawing different Plots

b
CLO 4. Demonstrate working with Seaborn, and Bokeh.

La
CLO 5. Working with Plotly for 3D, Time Series, and Maps.

on
Note: A two-hour tutorial is suggested for each laboratory session.

th
Py
Pedagogy: For the above experiments the following pedagogy can be considered. Problem-based
learning, Active learning, MOOC, Chalk &Talk

ith
PART A – List of problems for which students should develop programs and execute in the

w
Laboratory.
Course outcomes (Course Skill Set):
n
io
at
At the end of the course, the student will be able to:
iz

CO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications


al

CO 2. Use Python programming constructs to develop programs for solving real-world problems
su

CO 3. Use Matplotlib for drawing different Plots


CO 4. Demonstrate working with Seaborn, Bokeh for visualization.
Vi

CO 5. Use Plotly for drawing Time Series and Maps.


a
at
-D
D
58
S3
BC
IT
R
M
C

2 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
List of Problems/Experiments

an
M
Experiments

b
PART A – List of problems for which students should develop the program and execute it in the

La
laboratory

1 a) Write a Python program to find the best of two test average marks out of three test marks accepted

on
by the user.

th
b) Develop a Python program to check whether a given number is palindrome or not and also count

Py
the number of occurrences of each digit in the input number.
Datatypes: https://www.youtube.com/watch?v=gCCVsvgR2KU
Operators: https://www.youtube.com/watch?v=v5MR5JnKcZI

ith
Flow Control: https://www.youtube.com/watch?v=PqFKRqpHrjw

w
For loop: https://www.youtube.com/watch?v=0ZvaDa8eT5s
While loop: https://www.youtube.com/watch?v=HZARImviDxg

n
Exceptions: https://www.youtube.com/watch?v=6SPDvPK38tw
io
at
2 a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value for N
iz

(where N >0) as input and pass this value to the function. Display a suitable error message if the
al

condition for input value is not followed.


b) Develop a Python program to convert binary to decimal, and octal to hexadecimal using functions.
su

Functions:https://www.youtube.com/watch?v=BVfCWuca9nw
Vi

Arguments:https://www.youtube.com/watch?v=ijXMGpoMkhQ
Return value: https://www.youtube.com/watch?v=nuNXiEDnM44
a
at

3 a) Write a Python program that accepts a sentence and finds the number of words, digits, uppercase
-D

letters and lowercase letters.


b) Write a Python program to find the string similarity between two given strings.
Sample Output: Sample Output:
D

Original string: Original string:


58

Python Exercises Python Exercises


S3

Python Exercises Python Exercise


Similarity between two said strings: 1.0 Similarity between two said strings:0.967741935483871
BC

Strings: https://www.youtube.com/watch?v=lSItwlnF0eU
String functions: https://www.youtube.com/watch?v=9a3CxJyTq00
IT

4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
R

b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
M

https://www.youtube.com/watch?v=RRHQ6Fs1b8w&list=PLjVLYmrlmjGcC0B_FP3bkJ-JIPkV5Gu
ZR&index=3
C

https://www.youtube.com/watch?v=7ABCuhWO9II&list=PLjVLYmrlmjGcC0B_FP3bkJ-JIPkV5Gu
ZR&index=4

3 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
5 a) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.

ua
b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
https://www.youtube.com/watch?v=Qk7caotaQUQ&list=PLjVLYmrlmjGcC0B_FP3bkJ-JIPkV5GuZ

an
R&index=6

M
https://www.youtube.com/watch?v=PSji21jUNO0&list=PLjVLYmrlmjGcC0B_FP3bkJ-JIPkV5GuZ
R&index=7

b
La
6 a) Write a Python program to illustrate Linear Plotting using Matplotlib
b) Line Plot Illustration with Matplotlib.

on
https://www.youtube.com/watch?v=UO98lJQ3QGI&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB

th
7 Write a Python program that explains the uses of customizing seaborn plots with Aesthetic functions.

Py
https://www.youtube.com/watch?v=6GUZXDef2U0

8 a) Write a Python program to explain working with a bokeh line graph using Annotations and

ith
Legends.

w
b) Write a Python program for plotting different types of plots using Bokeh.
https://www.youtube.com/watch?v=HDvxYoRadcA

n
9
io
Write a Python program to draw 3D Plots using Plotly Libraries.
at
https://www.youtube.com/watch?v=cCck7hCanpw&list=PLE50-dh6JzC4onX-qkv9H3HtPbBVA8M
iz

94&index=4
al

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


su

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


Vi

https://www.youtube.com/watch?v=xnJ2TNrGYik&list=PLE50-dh6JzC4onX-qkv9H3HtPbBVA8M9
4&index=5
a

https://www.youtube.com/watch?v=D35m2CdMhVs&list=PLE50-dh6JzC4onX-qkv9H3HtPbBVA8
at

M94&index=6
-D
D
58
S3
BC
IT
R
M
C

4 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 1(a): Best Test Average Calculator

an
Problem Statement: Write a Python program to find the best of two test average marks out of

M
three test’s marks accepted from the user.

b
Algorithm:

La
1. Define a function calculate_average(scores) which takes a list of scores and returns their
average.

on
2. Prompt the user to input the score for test1, test2, and test3.

th
3. Calculate the average of test1 and test2 using the calculate_average function and store it
in average1.

Py
4. Calculate the average of test2 and test3 using the calculate_average function and store it
in average2.

ith
5. Compare the averages:
6. If average1 is greater than average2, print the message indicating that the best average is

w
from tests 1 and 2.

n
7. If average1 is less than average2, print the message indicating that the best average is
io
from tests 2 and 3.
at
8. If both averages are equal, print the message indicating that the averages are equal.
iz

9. End of algorithm.
al

Code:
su

m1 = int(input("Enter marks for test1 : "))


Vi

m2 = int(input("Enter marks for test2 : "))


a
at

m3 = int(input("Enter marks for test3 : "))


-D

if m1 <= m2 and m1 <= m3:


avgMarks = (m2+m3)/2
D

elif m2 <= m1 and m2 <= m3:


58
S3

avgMarks = (m1+m3)/2
elif m3 <= m1 and m2 <= m2:
BC

avgMarks = (m1+m2)/2
IT

print("Average of best two test marks out of three test’s marks is", avgMarks);
R

Results:
M

Enter marks for test1: 45


C

Enter marks for test2: 39


Enter marks for test3: 48

5 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Average of best two test marks out of three test’s marks is 46.5

an
Learning Outcomes:

M
Students will acquire proficiency in calculating and comparing averages of test scores, gaining a
practical understanding of data analysis techniques.

b
La
on
th
Py
ith
w
n
io
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

6 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 1(b): Palindrome Number Checking

an
Problem Statement: Develop a Python program to check whether a given number is palindrome

M
or not and also count the number of occurrences of each digit in the input number.

b
Algorithm:

La
1. Define a function is_palindrome(num):
2. This function checks if a given number num is a palindrome.

on
3. It does this by converting the number to a string, and then comparing it with its reverse.

th
4. Define a function count_occurrences(num):

Py
1) This function counts the occurrences of each digit in a given number num.
2) It initializes a list called digit_count with 10 elements, all set to 0 (to count

ith
occurrences of digits 0-9).
5. Inside count_occurrences:

w
6. Convert the input number num to a string to iterate through its digits.

n
7. For each digit in the string representation of num:
io
3) Convert the digit back to an integer and use it as an index to update the
at
corresponding element in digit_count.
4) After processing all digits, return the digit_count list which now contains the
iz

counts of each digit.


al

8. In the main program:


su

9. Prompt the user to enter a number using the input() function.


Vi

10. Convert the user's input to an integer.


11. Check if the entered number is a palindrome using the is_palindrome function:
a
at

12. If it is a palindrome, print a message indicating so.


13. If it is not a palindrome, print a message indicating that it's not.
-D

14. Call the count_occurrences function with the entered number to get the list of digit
occurrences.
D

15. Iterate through the digit_count list:


58

5) For each index (representing a digit), if the count is greater than 0:


S3

6) Print a message indicating how many times that digit occurs.


BC

Code:
val = int(input("Enter a value : "))
IT

str_val = str(val)
R

if str_val == str_val[::-1]:
M
C

print("Palindrome")
else:

7 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
print("Not Palindrome")

l
ua
for i in range(10):

an
if str_val.count(str(i)) > 0:

M
print(str(i),"appears", str_val.count(str(i)), "times");

b
Result:

La
Enter a value: 1234234

on
Not Palindrome

th
1 appears 1 times

Py
2 appears 2 times

ith
3 appears 2 times

w
4 appears 2 times

n
Enter a value: 12321
io
at
Palindrome
iz

1 appears 2 times
al
su

2 appears 2 times
Vi

3 appears 1 times
a

Learning Outcomes:
at
-D

Students will demonstrate a deep understanding of fundamental concepts and principles within
the specified subject area. Students will apply critical thinking and problem-solving skills to
analyze, evaluate, and solve complex problems related to the subject matter.
D
58
S3
BC
IT
R
M
C

8 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 2(a): Fibonacci Sequence Generator with Error Handling

an
Problem Statement: Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program that

M
accepts a value for N (where N >0) as input and passes this value to the function. Display a
suitable error message if the condition for input value is not followed.

b
La
Algorithm:
1. Define a recursive function F(n) to calculate the Fibonacci sequence.

on
2. If n is less than or equal to 0, raise a ValueError with the message "Input value should be

th
greater than 0."

Py
3. If n is 1, return 0.
4. If n is 2, return 1.

ith
5. Otherwise, recursively call F(n-1) + F(n-2).
6. Implement a try block:

w
7. Inside the try block:

n
a. Prompt the user to enter a value for N (where N > 0) using the input() function.
io
b. Convert the input to an integer and store it in the variable N.
at
8. Call the function F(N) with the user-provided value N.
iz

9. If successful, store the result in the variable result.


10. Print the Fibonacci value for F(N).
al

11. Implement an except block to handle a ValueError:


su

a. If a ValueError is raised (if N is less than or equal to 0), catch the exception and
Vi

print the error message.


a

Code:
at
-D

def fn(n):
if n == 1:
D

return 0
58

elif n == 2:
S3

return 1
BC

else:
IT

return fn(n-1) + fn(n-2)


R
M

num = int(input("Enter a number : "))


C

9 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
if num > 0:

l
ua
print("fn(", num, ") = ",fn(num) , sep ="")

an
else:

M
print("Error in input")

b
Result:

La
Enter a number : 5

on
fn(5) = 3

th
Enter a number : -5

Py
Error in input

ith
Learning Outcome:

w
Students will demonstrate proficiency in applying advanced problem-solving techniques within

n
the specified subject area. Students will critically analyze complex concepts and communicate
io
their understanding effectively through written and oral presentations.
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

10 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 2(b):Binary-to-Decimal and Octal-to-Hexadecimal Converter

an
Problem Statement: Develop a Python program to convert binary to decimal, and octal to

M
hexadecimal using functions.

b
Algorithm:

La
1. Define a function binary_to_decimal(binary):
a. Initialize a variable decimal to 0.

on
b. Iterate through each digit in the binary string.

th
c. For each digit, multiply decimal by 2 and add the integer value of the digit.

Py
d. Return the resulting decimal value.
2. Define a function octal_to_hexadecimal(octal):

ith
a. Convert the octal input to a decimal integer using int(octal, 8).
b. Convert the decimal integer to a hexadecimal string, remove the '0x' prefix, and

w
convert to uppercase using hex(decimal)[2:].upper().

n
c. Return the resulting hexadecimal string.
io
3. Get user input for the conversion type using input().
at
4. Convert the user's input to uppercase.
iz

5. Use an if-elif-else structure to perform the desired conversion:


a. If conversion_type is 'B':
al

i. Prompt the user to enter a binary number using input().


su

ii. Call the binary_to_decimal function and store the result in decimal_result.
Vi

iii. Print the decimal equivalent.


b. If conversion_type is 'O':
a
at

i. Prompt the user to enter an octal number using input().


ii. Call the octal_to_hexadecimal function and store the result in
-D

hexadecimal_result.
iii. Print the hexadecimal equivalent.
D

6. If the input is neither 'B' nor 'O', print an error message.


58

Code:
S3

def bin_to_dec():
BC

bin=int(input("Enter a binary number : "))


IT

dec=0
R

i=0
M

while bin!=0:
C

dec+=(bin%10)*(2**i)

11 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
i+=1

l
ua
bin//=10

an
print("Decimal Equivalent is : ",dec)

M
def oct_to_hex():

b
oct=int(input("Enter an octal number : "))

La
dec=0

on
i=0

th
while oct!=0:

Py
dec+=(oct%10)*(8**i)

ith
i+=1

w
oct//=10

n
hex =""
io
at
while dec!=0:
iz

rem=dec%16
al
su

if rem<10:
Vi

hex+=str(rem)
a

else:
at

hex+= chr(ord('A')+rem-10)
-D

dec//=16
D

hex=hex[::-1]
58

print("Hexadecimal Equivalent is : ", hex)


S3

print("BINARY TO DECIMAL CONVERSION")


BC

bin_to_dec()
IT

print("\n\nOCTAL TO HEXADECIMAL CONVERSION")


R

oct_to_hex()
M
C

12 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
Result:

l
ua
an
M
b
La
Learning Outcome:

on
Students will demonstrate proficiency in converting between different number systems, including

th
binary-to-decimal and octal-to-hexadecimal, using Python programming. Students will apply
critical thinking and problem-solving skills to design and implement efficient conversion

Py
functions, enhancing their computational proficiency.

ith
w
n
io
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

13 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 3(a): Sentence Analyzer: Words, Digits, Uppercase, and Lowercase Counter

an
Problem Statement: Write a Python program that accepts a sentence and find the number of

M
words, digits, uppercase letters and lowercase letters.

b
Algorithm:

La
1. Define a function named analyze_sentence that takes a sentence as input.
2. Create variables to store counts for words, digits, uppercase letters, and lowercase letters.

on
Initialize all counters to 0.

th
3. Use the split() method to split the sentence into a list of words. Store it in a variable like

Py
words.
4. Calculate the number of words by finding the length of the words list.

ith
5. Iterate through each character in the sentence.
6. Check for Digits, Uppercase, and Lowercase Letters:

w
a. For each character:

n
i. Check if it is a digit using isdigit(). If true, increment the digit counter.
io
ii. Check if it is an uppercase letter using isupper(). If true, increment the
at
uppercase counter.
iz

iii. Check if it is a lowercase letter using islower(). If true, increment the


lowercase counter.
al

7. Return the counts for words, digits, uppercase letters, and lowercase letters.
su

8. Prompt the user to enter a sentence using input().


Vi

9. Call the analyze_sentence function with the user-provided sentence as an argument. Store
the results in variables.
a
at

10. Print the results to the console, indicating the number of words, digits, uppercase letters,
and lowercase letters in the sentence.
-D

11. The program execution is complete.


D

Code:
58

sentence = input("Enter a sentence: ")


S3

words = digits = upper = lower = 0


BC
IT

# Splitting the sentence using split() method , by default split is by spaces


R

# Return value - list of strings


M
C

split_sentence = sentence.split()
print("The result of split() on input sentence is : \n"+str(split_sentence)+"\n")

14 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
words = len(split_sentence )

an
for c in sentence:

M
if c.isdigit():

b
digits = digits + 1

La
elif c.isupper():

on
upper = upper + 1

th
elif c.islower():

Py
lower = lower + 1

ith
print ("No of Words: ", words)

w
print ("No of Digits: ", digits)

n
print ("No of Uppercase letters: ", upper)
io
at
print ("No of Lowercase letters: ", lower)
iz

Result:
al
su

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


Vi

The result of split() on input sentence is :


a

['Rama', 'went', 'to', 'Devaraja', 'market', 'to', 'pick', '2', 'kgs', 'of', 'vegetable']
at

No of Words: 11
-D

No of Digits: 1
D

No of Uppercase letters: 2
58

No of Lowercase letters: 42
S3

Learning Outcome:
BC

Develop proficiency in using Python to analyze and manipulate textual data, demonstrating skills
IT

in string manipulation and iteration. Apply critical thinking to design and implement a program
that counts words, digits, uppercase letters, and lowercase letters, enhancing their ability to
R

process and analyze textual information.


M
C

15 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 3(b): String Similarity Checker

an
Problem Statement: Write a Python program to find the string similarity between two given

M
strings

b
Algorithm:

La
1. Define a function (e.g., string_similarity) that takes two strings as input.
2. Choose a similarity metric (e.g., Levenshtein distance, Jaccard similarity, etc.) based on

on
the specific requirements.

th
3. Inside the function, use the chosen similarity metric to calculate the similarity score

Py
between the two strings.
4. Return the computed similarity score.

ith
5. Prompt the user to enter the two strings.
6. Call the function string_similarity with the user-provided strings as arguments.

w
7. Print or display the similarity score between the two strings.

n
8. The program execution is complete. io
Code:
at
iz

str1 = input("Enter String 1 \n")


al

str2 = input("Enter String 2 \n")


su

if len(str2) < len(str1):


Vi

short = len(str2)
a
at

long = len(str1)
-D

else:
D

short = len(str1)
58

long = len(str2)
S3

matchCnt = 0
BC

for i in range(short):
if str1[i] == str2[i]:
IT

matchCnt += 1
R
M

print("Similarity between two said strings:")


C

print(matchCnt/long)

16 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
Result:

l
ua
Enter String 1

an
Python Exercises

M
Enter String 2

b
Python Exercises

La
Similarity between two said strings:

on
1.0

th
Enter String 1

Py
Python Exercises

ith
Enter String 2

w
Python Exercise

n
io
Similarity between two said strings: 0.9375
at
Learning Outcome:
iz

Apply a chosen string similarity metric (e.g., Levenshtein distance, Jaccard similarity) to
al

quantitatively measure the similarity between two given strings. Develop proficiency in using
su

Python to implement and utilize string similarity algorithms, enhancing their ability to analyze
Vi

and compare textual data effectively.


a
at
-D
D
58
S3
BC
IT
R
M
C

17 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 4(a): Matplotlib Bar Plot Demonstration

an
Problem Statement: Write a Python program to Demonstrate how to Draw a Bar Plot using

M
Matplotlib.

b
Algorithm:

La
1. Import the necessary module from Matplotlib to create plots.
2. Define the data you want to plot (e.g., categories and values).

on
3. Use plt.bar() to create a bar plot.

th
4. Provide the categories and corresponding values as arguments.

Py
5. Optionally, specify the colors for the bars.
6. Use plt.title() to set a title for the plot.

ith
7. Use plt.xlabel() and plt.ylabel() to label the x and y axes, respectively.
8. Use plt.show() to display the plot.

w
9. The program execution is complete.
Dataset: Cars.csv is used.
n
io
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

Code:
# Import the necessary modules

18 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
import matplotlib.pyplot as plt

an
import pandas as pd

M
# Initialize the lists for X and Y

b
data = pd.read_csv("Car_Barplot.csv")

La
df = pd.DataFrame(data)

on
X = list(df.iloc[:, 0])

th
Y = list(df.iloc[:, 1])

Py
# Plot the data using bar() method

ith
plt.bar(X, Y, color='g')

w
plt.title("Used Car Sales")

n
plt.xlabel("Car")
io
at
plt.ylabel("Number Sold")
iz

# Show the plot


al
su

plt.show()
Vi

Result:
a
at
-D
D
58
S3
BC
IT
R
M
C

19 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Learning Outcome:

an
Demonstrate proficiency in using Matplotlib, a popular Python library, to create visualizations

M
such as bar plots. Apply knowledge of data visualization techniques to represent categorical data
effectively, enhancing their ability to communicate insights from datasets.

b
La
Title 4(b): Matplotlib Scatter Plot Demonstration
Problem Statement: Write a Python program to Demonstrate how to Draw a Scatter Plot using

on
Matplotlib.

th
Algorithm:

Py
1. Import the necessary module from Matplotlib to create plots.

ith
2. Define the x and y coordinates for the data points.
3. Use plt.scatter() to create a scatter plot.

w
4. Provide the x and y coordinates as arguments.

n
5. Optionally, specify the color and label for the points.
io
6. Use plt.title() to set a title for the plot.
at
7. Use plt.xlabel() and plt.ylabel() to label the x and y axes, respectively.
iz

8. If applicable, use plt.legend() to add a legend to the plot.


al

9. Use plt.show() to display the scatter plot.


10. The program execution is complete.
su
Vi

Code:
# import the necessary libraries
a
at

import pandas as pd
-D

import numpy as np
D

import matplotlib.pyplot as plt


58

# Importing data.
S3

cars_data = pd.read_csv("Toyota.csv")
BC

# Create scatter plot using two variables, Age and Price.


IT

plt.scatter(cars_data['Age'],cars_data['Price'],c='blue')
R

# To set the title


M

plt.title('Scatter plot of Price vs Age of the Cars')


C

# To set the x and y axis labels.


plt.xlabel('Age (months)')

20 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
plt.ylabel('Price (Euros)')

an
# To show the scatter plot

M
plt.show()

b
Result:

La
on
th
Py
ith
w
n
io
at
iz
al
su
Vi
a
at
-D

Learning Outcome:
D

Apply their knowledge of Matplotlib to create effective visualizations, specifically scatter plots,
58

for representing and analyzing data. Gain proficiency in conveying relationships between
S3

variables through graphical representations, enhancing their data visualization skills.


BC
IT
R
M
C

21 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 5(a): Matplotlib Histogram Plot Demonstration

an
ProblemStatement: Write a Python program to Demonstrate how to Draw a Histogram Plot

M
using Matplotlib.

b
Algorithm:

La
1. Import matplotlib. pyplot as plt for plotting.
2. Optionally, import numpy as np for generating example data.

on
3. Generate or obtain the dataset that you want to visualize with a histogram.

th
4. Use plt.hist() to create a histogram.

Py
5. Provide the data as the first argument.
6. Specify the number of bins using the bins parameter. This determines the number of

ith
intervals.
7. Optionally, specify the color and edge color for the bars.

w
8. Use plt.title() to set a title for the plot.

n
9. Use plt.xlabel() and plt.ylabel() to label the x and y axes, respectively.
io
10. Use plt.show() to display the histogram plot.
at
11. The program execution is complete.
iz

Code:
al

import matplotlib.pyplot as plt


su
Vi

import numpy as np
# Generate random data for the histogram
a
at

data = np.random.randn(50) # Example data


-D

# Create a histogram plot


D

plt.hist(data, bins=5, color='green', edgecolor='black')


58

# Add title and labels


S3

plt.title('Histogram Plot Example')


BC

plt.xlabel('Values')
IT

plt.ylabel('Frequency')
R

# Display the plot


M

plt.show()
C

Result:

22 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al

Learning Outcome:
su

Demonstrate proficiency in using Matplotlib to create effective visualizations, specifically


Vi

histogram plots, for analyzing and representing data distributions. Apply knowledge of
histogram parameters (e.g., number of bins) to appropriately visualize different types of datasets,
a
at

enhancing their data visualization skills.


-D
D
58
S3
BC
IT
R
M
C

23 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 5(b): Matplotlib Pie Chart Demonstration

an
Problem Statement: Write a Python program to Demonstrate how to Draw a Pie Chart using

M
Matplotlib.

b
Algorithm:

La
1. Import matplotlib.pyplot as plt for plotting.
2. Define the categories (labels), sizes (proportions), and colors for the pie chart.

on
3. Use plt.pie() to create a pie chart.

th
4. Provide sizes as input for the proportions of each category.

Py
5. Specify labels for the category labels.
6. Use autopct to display percentages on the chart.

ith
7. Use startangle to set the initial angle of the pie chart.
8. Use plt.axis('equal') to ensure that the pie chart is drawn as a circle.

w
9. Use plt.title() to set a title for the pie chart.

n
10. Use plt.show() to display the pie chart. io
11. The program execution is complete.
at
Code:
iz
al

import matplotlib.pyplot as plt


su

# Data
Vi

categories = ['Category A', 'Category B', 'Category C', 'Category D']


a

sizes = [30, 20, 25, 25]


at
-D

colors = ['blue', 'green', 'red', 'purple']


# Create a pie chart
D

plt.pie(sizes, labels=categories, colors=colors, autopct='%1.1f%%', startangle=140)


58
S3

# Equal aspect ratio ensures that pie is drawn as a circle.


BC

plt.axis('equal')
# Add title
IT

plt.title('Pie Chart Example')


R

# Display the plot


M
C

plt.show()

24 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
Learning Outcome:
iz

Demonstrate proficiency in using Matplotlib to create effective visualizations, specifically pie


al

charts, for representing categorical data in a clear and concise manner. Apply knowledge of pie
su

chart parameters (e.g., labels, colors, percentages) to effectively convey proportions and
Vi

distributions, enhancing their data visualization skills.


a
at
-D
D
58
S3
BC
IT
R
M
C

25 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 6(a): Matplotlib Linear Plot Illustration

an
Problem Statement: Write a Python program to illustrate Linear Plotting using Matplotlib.

M
Algorithm:

b
1. Import matplotlib.pyplot as plt for plotting.

La
2. Define the x and y coordinates for the linear plot.
3. Use plt.plot() to create a linear plot.

on
4. Provide the x and y coordinates as arguments.

th
5. Use plt.title() to set a title for the plot.

Py
6. Use plt.xlabel() and plt.ylabel() to label the x and y axes, respectively.
7. Use plt.show() to display the linear plot.

ith
8. The program execution is complete.

w
Code:

n
import matplotlib.pyplot as plt io
def linear_plot():
at
iz

# Sample data
al

x = [1, 2, 3, 4, 5]
su

y = [3, 7, 9, 11, 14]


Vi

# Plotting the data


a
at

plt.plot(x, y, label='Linear Function: y = 2x')


-D

# Adding labels and title


D

plt.xlabel('X-axis')
58

plt.ylabel('Y-axis')
S3

plt.title('Linear Plot Example')


BC

plt.legend()
plt.show()
IT

# Call the function to generate the plot


R
M

linear_plot()
C

26 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Result:

an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al

Learning Outcome:
su
Vi

Demonstrate proficiency in utilizing Matplotlib to create effective linear plots, enabling visual
representation of relationships between variables. Apply knowledge of plot customization and
a

labeling to effectively communicate data trends and insights through graphical representation.
at
-D
D
58
S3
BC
IT
R
M
C

27 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 6(b): Line Plot Illustration with Matplotlib

an
Problem Statement: Write a Python program to illustrate liner plotting with line formatting

M
using Matplotlib.

b
Algorithm:

La
1. Define lists x and y containing the data points.
2. Use plt.plot(x, y, marker='o', linestyle='-', color='b', label='Line Plot'):

on
3. x and y: Data points for the plot.

th
4. marker='o': Circular markers.

Py
5. linestyle='-': Solid line style.
6. color='b': Blue color for the line.

ith
7. label='Line Plot':
8. Use plt.xlabel('X-axis') and plt.ylabel('Y-axis') to label the x and y axes.

w
9. Use plt.title('Linear Plot with Line Formatting') to set the title of the plot.

n
10. Use plt.legend() to include a legend based on the label provided in plt.plot().
io
11. Use plt.show() to display the plot.
at
12. The program execution is complete.
iz

Code:
al

import matplotlib.pyplot as plt


su
Vi

def formatted_linear_plot():
# Sample data
a
at

x = [1, 2, 3, 4, 5, 6]
-D

y = [3, 7, 9, 11, 14, 18]


D

plt.plot(x, y, marker='o', linestyle='-', color='b', label='Linear Function: y = 2x')


58

# Adding labels and title


S3

plt.xlabel('X-axis')
BC

plt.ylabel('Y-axis')
IT

plt.title('Formatted Linear Plot Example')


R

plt.legend()
M

plt.grid(True) # Add a grid for better readability


C

plt.show()
# Call the function to generate the formatted linear plot

28 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
formatted_linear_plot()

l
ua
Result:

an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
su

Learning Outcome:
Vi

Gain proficiency in creating customized linear plots using Matplotlib, understanding key
parameters like markers, line styles, and colors for effective data visualization. Develop the
a
at

ability to label axes, add titles, and include legends, enhancing the clarity and interpretability of
generated plots for analytical purposes.
-D
D
58
S3
BC
IT
R
M
C

29 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 7: Customizing Scatter Plots with Seaborn Aesthetic Functions

an
Problem Statement: Write a Python program which explains uses of customizing seaborn plots

M
with Aesthetic functions.

b
Algorithm:

La
1. Import seaborn as sns for creating the scatter plot using Seaborn.
2. Import matplotlib.pyplot as plt for additional customization.

on
3. Load a sample dataset (in this case, "tips") using sns.load_dataset("tips").

th
4. Use sns.scatterplot(x="total_bill", y="tip", data=tips) to generate a scatter plot with

Py
total_bill on the x-axis and tip on the y-axis.
5. Use sns.set_style("whitegrid") to set the style of the plot (options include "darkgrid",

ith
"whitegrid", "dark", "white", and "ticks").
6. Customize Plot Labels and Title:

w
7. Set the title with plt.title("Scatter Plot with Seaborn").

n
8. Label the x-axis with plt.xlabel("Total Bill ($)").
io
9. Label the y-axis with plt.ylabel("Tip ($)").
at
10. Use plt.show() to display the scatter plot.
iz

Code:
al

import seaborn as sns


su
Vi

import matplotlib.pyplot as plt


# Load sample data
a
at

tips = sns.load_dataset("tips")
-D

# Create a scatter plot with Seaborn


D

sns.scatterplot(x="total_bill", y="tip", data=tips)


58

# Customize the plot using aesthetic functions


S3

sns.set_style("whitegrid") # Set the style to whitegrid


BC

plt.title("Scatter Plot with Seaborn")


IT

plt.xlabel("Total Bill ($)")


R

plt.ylabel("Tip ($)")
M

# Show the plot


C

plt.show()

30 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
Result:

l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
su

Learning Outcome:
Vi

Gain proficiency in creating visually appealing scatter plots using Seaborn and understand how
to enhance them further with aesthetic functions. Develop the ability to apply customization
a
at

techniques such as setting styles, labels, and titles to effectively communicate information
through data visualization.
-D
D
58
S3
BC
IT
R
M
C

31 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 8(a): Enhancing Line Graphs with Annotations and Legends using Bokeh

an
Problem Statement: Write a Python program to explain working with bokeh line graph using

M
Annotations and Legends.

b
Algorithm:

La
1. Import figure, show, and output_file from bokeh.plotting for creating and displaying
plots.

on
2. Import Label from bokeh.models for adding annotations.

th
3. Define lists x and y containing the data points.

Py
4. Create a new plot p with a specified title, x-axis label, y-axis label, and dimensions.
5. Add a line to the plot using p.line() with specified attributes like color, width, and legend

ith
label.
6. Create an annotation with Label() and add it to the plot using p.add_layout().

w
7. Optionally, specify an output file with output_file() (optional).

n
8. Use show(p) to display the Bokeh plot with the added annotations and legend.
io
Code:
at
iz

from bokeh.plotting import figure, show, output_file


al

from bokeh.models import Label


su

# Define data
Vi

x = [1, 2, 3, 4, 5]
a
at

y = [2, 3, 5, 7, 11]
-D

# Create a new plot


D

p = figure(title="Bokeh Line Graph with Annotations and Legends", x_axis_label='X-axis',


y_axis_label='Y-axis', width=600, height=400)
58
S3

# Add a line to the plot


BC

p.line(x, y, line_color="blue", line_width=2, legend_label="Line Plot")


# Add an annotation
IT

annotation = Label(x=3, y=7, text="Important Point", text_color="red")


R

p.add_layout(annotation)
M
C

# Add a legend
p.legend.location = "top_left"

32 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
# Specify an output file (optional)

an
output_file("bokeh_line_graph.html")

M
# Show the plot

b
show(p)

La
Result:

on
th
Py
ith
w
n
io
at
iz
al
su
Vi
a
at
-D

Learning Outcome:
D
58

Acquire proficiency in creating dynamic line graphs using Bokeh, and understand how to
enhance visualizations with annotations and legends for effective data communication. Develop
S3

the ability to add informative annotations and legends to plots, enabling clearer representation
BC

and interpretation of data trends and significant points.


IT
R
M
C

33 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 8(b): Bokeh Showcase: Exploring Diverse Plot Types

an
Problem Statement: Write a Python program for plotting different types of plots using Bokeh.

M
Algorithm:

b
1. Import Libraries:

La
2. Import necessary functions and modules from the Bokeh library.
3. Import NumPy for numerical operations.

on
4. Set Output Configuration:

th
5. Use output_file to specify the output file for the plots.

Py
6. Line Plot:
7. Create a new figure (p1) for the line plot.

ith
8. Set title, x-axis label, and y-axis label for the plot.
9. Create a line plot with x-values [1, 2, 3, 4, 5] and y-values [6, 7, 2, 4, 8] in blue.

w
10. Display the plot using show(p1).

n
11. Scatter Plot: io
12. Create a new figure (p2) for the scatter plot.
at
13. Set title, x-axis label, and y-axis label for the plot.
iz

14. Create a scatter plot using flowers['petal_length'] as x-values and flowers['petal_width']


as y-values.
al

15. Set the size of the circles to 10, color to green, and alpha (transparency) to 0.5.
su

16. Display the plot using show(p2).


Vi

17. Bar Plot:


18. Define categories (['A', 'B', 'C', 'D', 'E']) and corresponding values ([4, 7, 1, 8, 5]).
a
at

19. Create a new figure (p3) for the bar plot with specified x-range (categories).
20. Set title, x-axis label, and y-axis label for the plot.
-D

21. Create a vertical bar chart using vbar with specified x-values, top values (heights), width,
and color.
D

22. Hide the toolbar for this plot.


58

23. Display the plot using show(p3).


S3

24. Histogram:
25. Create a new figure (p4) for the histogram.
BC

26. Set title, x-axis label, and y-axis label for the plot.
27. Use NumPy to compute the histogram (hist) and bin edges (edges) for the 'petal_length'
IT

data with 20 bins.


28. Create a histogram using quad with specified top (histogram heights), bottom (always 0),
R

left (bin edges), right (bin edges), and colors.


M

29. Display the plot using show(p4).


C

30. Output Files:


31. Each plot is saved in a separate HTML file with the specified names (line_plot.html,
scatter_plot.html, bar_plot.html, histogram.html).

34 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
32. Execution:
33. The code executes sequentially, generating and displaying each plot one after the other.

an
Code:

M
from bokeh.plotting import figure, show, output_file

b
La
from bokeh.io import output_notebook
from bokeh.sampledata.iris import flowers

on
import numpy as np

th
Py
# Line Plot
output_file("line_plot.html")

ith
p1 = figure(title="Line Plot", x_axis_label='X-axis', y_axis_label='Y-axis')

w
p1.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 8], line_color="blue")

n
show(p1)
io
at
# Scatter Plot
iz
al

output_file("scatter_plot.html")
su

p2 = figure(title="Scatter Plot", x_axis_label='X-axis', y_axis_label='Y-axis')


Vi

p2.circle(flowers['petal_length'], flowers['petal_width'], size=10, color="green", alpha=0.5)


a
at

show(p2)
-D

# Bar Plot
categories = ['A', 'B', 'C', 'D', 'E']
D
58

values = [4, 7, 1, 8, 5]
S3

output_file("bar_plot.html")
BC

p3 = figure(x_range=categories, title="Simple Bar Chart",


x_axis_label='Categories', y_axis_label='Values',
IT

toolbar_location=None, tools="")
R
M

p3.vbar(x=categories, top=values, width=0.5, color="blue")


C

show(p3)
# Histogram

35 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
output_file("histogram.html")

an
p4 = figure(title="Histogram", x_axis_label='Values', y_axis_label='Frequency')

M
hist, edges = np.histogram(flowers['petal_length'], bins=20)

b
p4.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="orange",

La
line_color="black")

on
show(p4)

th
Py
Result:

ith
w
n
io
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

36 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

37 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
an
M
b
La
on
th
Py
ith
w
Learning Outcome:
n
io
at
Gain proficiency in generating various types of plots including line plots, scatter plots, bar
iz

charts, and histograms using the Bokeh library. Develop the ability to represent data effectively
al

through hands-on experience in designing and displaying different types of visualizations for
su

improved data understanding and communication.


Vi
a
at
-D
D
58
S3
BC
IT
R
M
C

38 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 9: Sinusoidal 3D Surface Exploration

an
Problem Statement: Write a Python program to draw 3D Plots using Plotly Libraries.

M
Algorithm:

b
1. Import necessary modules from the Plotly library (plotly.graph_objects).

La
2. Import NumPy for numerical operations.
3. Generate a set of x and y values using np.linspace to create a grid.

on
4. Use np.meshgrid to create a 2D grid of x and y values.

th
5. Calculate z-values based on a function of x and y (in this case, np.sin(np.sqrt(x**2 +

Py
y**2))).
6. Create 3D Surface Plot:

ith
7. Use go.Figure to initialize a new plot.
8. Add a 3D surface plot using go.Surface with the computed z-values, x-values, and

w
y-values.

n
9. Update the layout of the plot with a title and axis labels.
io
10. Set the title to "Sinusoidal 3D Surface Exploration".
at
11. Specify labels for the x, y, and z axes.
iz

12. Use fig.show() to display the 3D surface plot.


13. Ensure that the Plotly library is installed (pip install plotly).
al

14. Run the program, and it will generate and display the 3D surface plot.
su
Vi

Code:
import plotly.graph_objects as go
a
at

import numpy as np
-D

# Define the data


D

x = np.linspace(-5, 5, 100)
58

y = np.linspace(-5, 5, 100)
S3

x, y = np.meshgrid(x, y)
BC

z = np.sin(np.sqrt(x**2 + y**2))
IT

# Create the 3D surface plot


R

fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])


M

# Set the layout of the plot


C

fig.update_layout(
title='3D Surface Plot',

39 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
scene=dict(

an
xaxis_title='X-axis',

M
yaxis_title='Y-axis',

b
zaxis_title='Z-axis'

La
)

on
)

th
# Display the plot

Py
fig.show()

ith
Result:

w
n
io
at
iz
al
su
Vi
a
at
-D
D
58
S3
BC

Learning Outcome:
Gain the ability to create and customize 3D plots, enabling effective representation and
IT

exploration of multidimensional data using the Plotly library. Develop a comprehension of how
R

data points can be mapped and visualized in three-dimensional space, enhancing the capacity to
M

convey complex relationships visually.


C

40 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
Title 10 (a): visual exploration of Time Series Data

an
Problem Statement: Write a Python program to draw Time Series using Plotly Libraries.

M
Algorithm:

b
1. Import Necessary Libraries

La
2. plotly.graph_objects as go for creating plots.
3. datetime from the datetime module for handling dates.

on
4. Create a list dates containing datetime objects representing the dates.

th
5. Create a list values containing corresponding numerical values.

Py
6. Create a Trace
7. Create a Scatter trace:

ith
8. Use the go.Scatter function to create a trace.
9. Set the x attribute to dates and y attribute to values.

w
10. Set mode to 'lines+markers' for both lines and markers on the plot.

n
11. Create Layout io
12. Define the layout for the plot:
at
13. Create a layout using go.Layout.
iz

14. Set the title of the plot using title.


15. Set titles for the x-axis and y-axis using xaxis_title and yaxis_title.
al

16. Create a Figure


su

17. Combine the trace and layout into a Figure object:


Vi

18. Use go.Figure with the trace and layout as arguments.


19. Display the Plot
a
at

20. Show the plot on the screen:


21. Use fig.show() to display the plot.
-D

22. Run the Program


23. Execute the Python program to generate and display the Time Series plot.
D
58

Code:
S3

import plotly.express as px
BC

import pandas as pd
# Load the dataset (replace 'your_dataset.csv' with the actual file path)
IT

data = pd.read_csv("Rainfall_data.csv")
R
M

# Combine Year, Month, and Day columns to create a datetime column


C

data['Date'] = pd.to_datetime(data[['Year', 'Month', 'Day']])


# Create time series plot

41 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
fig = px.line(data, x='Date', y=[ 'Temperature'],

l
ua
title='Time Series Plot', labels={'value': 'Values'}, line_shape='linear')

an
fig.show()

M
Result:

b
La
on
th
Py
ith
w
n
io
at
iz
al
su
Vi

Learning Outcome:
a

Gain proficiency in visualizing temporal data through Time Series plots, enabling the analysis of
at

trends, patterns, and anomalies in time-dependent datasets. Develop the skills to customize and
-D

present Time Series plots effectively, enhancing the ability to communicate insights derived from
time-based data to stakeholders and decision-makers.
D
58
S3
BC
IT
R
M
C

42 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
an
Title 10 (b): Map Exploration using Plotly

M
Problem Statement: Write a Python program for creating Maps using Plotly Libraries.

b
Algorithm:

La
1. Import Necessary Libraries:

on
2. Import plotly.graph_objects as go for creating plots.
3. Use go.Choropleth to create a map visualization.

th
4. Set locations to ['IND'] to indicate India.

Py
5. Set z with data representing the population density of Indian states.
6. Provide hovertext to display additional information when hovering over the map.

ith
7. Define Layout for the Map:

w
8. Create a layout using go.Layout.
9. Optionally, customize the appearance, e.g., showing coastlines.
10. Create Figure:
n
io
11. Combine the trace and layout into a Figure object using go.Figure.
at
12. Display the Map:
iz

13. Use fig.show() to render and display the map.


al

14. Adjust the color scale, annotations, or other visual elements as needed.
su

15. Run the Program:


Vi

16. Execute the Python program to generate and display the India map.
Code:
a
at

import plotly.express as px
-D

# Sample data for demonstration


D

data = {
58

'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Houston'],


S3

'Lat': [40.7128, 37.7749, 34.0522, 41.8781, 29.7604],


BC

'Lon': [-74.0060, -122.4194, -118.2437, -87.6298, -95.3698],


IT

'Population': [8175133, 870887, 3971883, 2716000, 2328000]


R

}
M

# Create a map
C

fig = px.scatter_geo(data, lat='Lat', lon='Lon', text='City', size='Population',


projection='natural earth', title='Population of Cities')

43 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
fig.update_traces(textposition='top center')

an
fig show()

M
Result:

b
La
on
th
Py
ith
w
n
io
at
iz
al
su
Vi

Learning Outcome:
a
at

Gain proficiency in visualizing geographic data through interactive maps, enabling the effective
-D

communication of spatial information and trends. Develop skills in customizing maps with
specific geographical data, enhancing the ability to present location-based insights for various
D

analytical and reporting purposes.


58
S3
BC
IT
R
M
C

44 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
Content beyond syllabus:

ua
an
Title: Apply Visualization concept using Holoviews on Country Population Dataset

M
Problem Description:

b
You are provided with a dataset containing information about the population of various

La
countries. Your task is to create informative visualizations using Holoviews, a powerful data
visualization library in Python. The goal is to present key insights and trends in an interactive

on
and visually appealing manner.

th
Algorithm:

Py
Step 1: Install Required Packages

ith
Step 3: Load the Dataset

w
Step 4: Data Preprocessing

n
Step 5: Create a Scatter Plot io
Step 6: Display the Scatter Plot
at
iz

Code:
al

!pip install holoviews


su

!pip install hvplot


Vi

import holoviews as hv
a
at

from holoviews import opts


-D

import pandas as pd
D

df=pd.read_csv("Countries Population_1.csv") #Reading Csv file


58

df
S3

df['Population -2023']=df['Population -2023'].apply(lambda x: x.replace(",", ""))


BC

scatter = df.hvplot.scatter(x='World Share', y='Country (or dependency)', color='blue', size=5,


width=800, height=500) # Applying the hvplot library
IT

scatter
R
M
C

45 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
Results:

l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
su
Vi
a
at

Learning Outcomes:
-D

Learners will gain experience in data preprocessing techniques, such as cleaning and converting
data types, to enhance the effectiveness of visualizations, thereby improving their ability to
D

convey insights from the dataset.


58
S3
BC
IT
R
M
C

46 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python

l
ua
an
Title: Data visualization with list comprehension

M
Problem Description: Create a data visualization representing a list comprehension technique

b
for generating prime numbers. Display the sequence of prime numbers within a specified range,

La
showcasing the efficiency and elegance of this approach in generating prime numbers.
Algorithm:

on
1. Define a function generate_primes(start, end) to generate prime numbers within the

th
specified range.

Py
2. Initialize an empty list primes to store the generated prime numbers.
3. Iterate over each number in the range from start to end - 1.

ith
4. Check if the number is greater than 1.

w
5. If true, iterate over divisors from 2 to the square root of the number (inclusive).

n
6. Check if the number is divisible by any divisor.
io
7. If divisible, break the loop.
at
8. If not divisible by any divisor, add it to the primes list.
iz

9. Return the list of prime numbers.


al

10. Define a function visualize_primes(primes) to create a plot of the generated prime


su

numbers.
11. Use Matplotlib to plot the prime numbers with the x-axis representing the index and
Vi

y-axis representing the value of prime numbers.


a

12. Add labels to the x-axis ("Prime number index") and y-axis ("Prime number value").
at

13. Set the title of the plot to "Plot of prime numbers".


-D

14. Display the plot using plt.show().


Code:
D

import matplotlib.pyplot as plt


58
S3

def is_prime(n):
BC

if n <= 1:
return False
IT

if n == 2:
R

return True
M
C

if n % 2 == 0:
return False

47 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
for i in range(3, int(n**0.5) + 1, 2):

l
ua
if n % i == 0:

an
return False

M
return True

b
def prime_numbers_in_range(start, end):

La
return [i for i in range(start, end+1) if is_prime(i)]

on
th
# Define the range

Py
start = 1

ith
end = 100

w
# Generate prime numbers using list comprehension

n
io
prime_numbers = prime_numbers_in_range(start, end)
at
print(prime_numbers)
iz

plt.figure(figsize=(10, 6))
al
su

plt.plot(prime_numbers, linewidth=2)
Vi

plt.title('Prime Numbers in Range [{}, {}]'.format(start, end))


a

plt.xlabel('Index values')
at

plt.ylabel('Prime Numbers')
-D

plt.show()
D
58
S3
BC
IT
R
M
C

48 | Page CMRIT, Department of CSE


CMR Institute of Technology, Bengaluru
Department of Computer Science and Technology
LAB MANUAL, III SEMESTER, 2022 SCHEME
BCS358D - Data Visualization with Python
Result:

l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
su

Learning Outcomes:
Vi

Students will gain a comprehensive understanding of fundamental prime number generation


algorithms and their implementation in Python. They will develop proficiency in data
a
at

visualization using Matplotlib, enabling them to represent prime numbers graphically for
-D

analysis and interpretation.


D
58
S3
BC
IT
R
M
C

49 | Page CMRIT, Department of CSE

You might also like