DV_Lab_Manual_BCS358D.docx[1]
DV_Lab_Manual_BCS358D.docx[1]
DV_Lab_Manual_BCS358D.docx[1]
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
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 2. Use Python programming constructs to develop programs for solving real-world problems
su
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
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
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
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
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
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
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
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
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
14. Call the count_occurrences function with the entered number to get the list of digit
occurrences.
D
Code:
val = int(input("Enter a value : "))
IT
str_val = str(val)
R
if str_val == str_val[::-1]:
M
C
print("Palindrome")
else:
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
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
a. If a ValueError is raised (if N is less than or equal to 0), catch the exception and
Vi
Code:
at
-D
def fn(n):
if n == 1:
D
return 0
58
elif n == 2:
S3
return 1
BC
else:
IT
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
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
ii. Call the binary_to_decimal function and store the result in decimal_result.
Vi
hexadecimal_result.
iii. Print the hexadecimal equivalent.
D
Code:
S3
def bin_to_dec():
BC
dec=0
R
i=0
M
while bin!=0:
C
dec+=(bin%10)*(2**i)
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
bin_to_dec()
IT
oct_to_hex()
M
C
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
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
7. Return the counts for words, digits, uppercase letters, and lowercase letters.
su
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
Code:
58
split_sentence = sentence.split()
print("The result of split() on input sentence is : \n"+str(split_sentence)+"\n")
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
['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
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
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(matchCnt/long)
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
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
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
plt.show()
Vi
Result:
a
at
-D
D
58
S3
BC
IT
R
M
C
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
Code:
# import the necessary libraries
a
at
import pandas as pd
-D
import numpy as np
D
# Importing data.
S3
cars_data = pd.read_csv("Toyota.csv")
BC
plt.scatter(cars_data['Age'],cars_data['Price'],c='blue')
R
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
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 numpy as np
# Generate random data for the histogram
a
at
plt.xlabel('Values')
IT
plt.ylabel('Frequency')
R
plt.show()
C
Result:
l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
Learning Outcome:
su
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
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
# Data
Vi
plt.axis('equal')
# Add title
IT
plt.show()
l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
Learning Outcome:
iz
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
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
plt.xlabel('X-axis')
58
plt.ylabel('Y-axis')
S3
plt.legend()
plt.show()
IT
linear_plot()
C
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
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
def formatted_linear_plot():
# Sample data
a
at
x = [1, 2, 3, 4, 5, 6]
-D
plt.xlabel('X-axis')
BC
plt.ylabel('Y-axis')
IT
plt.legend()
M
plt.show()
# Call the function to generate the 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
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
tips = sns.load_dataset("tips")
-D
plt.ylabel("Tip ($)")
M
plt.show()
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
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
# Define data
Vi
x = [1, 2, 3, 4, 5]
a
at
y = [2, 3, 5, 7, 11]
-D
p.add_layout(annotation)
M
C
# Add a legend
p.legend.location = "top_left"
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
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
15. Set the size of the circles to 10, color to green, and alpha (transparency) to 0.5.
su
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
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
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
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
toolbar_location=None, tools="")
R
M
show(p3)
# Histogram
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
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
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
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
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
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
fig.update_layout(
title='3D Surface Plot',
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
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
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
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
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
14. Adjust the color scale, annotations, or other visual elements as needed.
su
16. Execute the Python program to generate and display the India map.
Code:
a
at
import plotly.express as px
-D
data = {
58
}
M
# Create a map
C
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
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
import holoviews as hv
a
at
import pandas as pd
D
df
S3
scatter
R
M
C
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
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
numbers.
11. Use Matplotlib to plot the prime numbers with the x-axis representing the index and
Vi
12. Add labels to the x-axis ("Prime number index") and y-axis ("Prime number value").
at
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
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.xlabel('Index values')
at
plt.ylabel('Prime Numbers')
-D
plt.show()
D
58
S3
BC
IT
R
M
C
l
ua
an
M
b
La
on
th
Py
ith
w
n
io
at
iz
al
su
Learning Outcomes:
Vi
visualization using Matplotlib, enabling them to represent prime numbers graphically for
-D