JSS MAHAVIDYAPEETHA
JSS ACADEMY OF TECHNICAL EDUCATION, BENGALURU-60
DEPARTMENT OF INFORMATION SCIENCE AND
ENGINEERING
JSSATE Campus, Dr. Vishnuvardhana Main Road, Bengaluru – 560060
III SEMESTER
DATA VISUALIZATION WITH PYTHON LABORATORY LAB
MANUAL
[BCS358D]
Compiled By:
Mr. Chetan R Mrs. Punitha M Mrs. Kavya T C
Assistant Professor, Assistant Professor, Assistant Professor,
Dept of Information Science & Dept of Information Science & Dept of Information Science &
Engineering, JSSATEB Engineering, JSSATEB Engineering, JSSATEB
Signature of Faculty Signature of HOD
JSS MAHAVIDYAPEETHA
JSS ACADEMY OF TECHNICAL EDUCATION, BENGALURU-60
DEPARTMENT OF INFORMATION SCIENCE AND
ENGINEERING
VISION
To emerge as a centre for achieving academic excellence, by producing competent professionals
to meet the global challenges in the field of Information science and Technology.
MISSION
M1: To prepare the students as competent professionals to meet the advancements in the
industry and academia by imparting quality technical education.
M2: To enrich the technical ability of students to face the world with confidence, commitment,
and teamwork
.
M3: To inculcate and practice strong techno-ethical values to serve the society.
Program Educational Objectives (PEOs):
PEO1: To demonstrate analytical and technical problem-solving abilities.
PEO2: To be conversant in the developments of Information Science and Engineering, leading
towards the employability and higher studies.
PEO3: To engage in research and development leading to new innovations and products.
Program Specific Outcomes (PSOs):
PSO1: Apply the mathematical concepts for solving engineering problems by using appropriate
programming constructs
.
PSO2: Adaptability to software development methodologies.
PSO3: Demonstrate the knowledge towards the domain specific initiatives of Information
Science and Engineering.
Program Outcomes (POs):
Information Science and Engineering Graduates will be able to:
PO1 Apply the knowledge of mathematics, science, engineering fundamentals, and an
Engineering specialization to the solution of complex engineering problems.
PO2 Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3 Design solutions for complex engineering problems and design system components or
processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental
considerations.
PO4 Use research-based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to provide valid
conclusions.
PO5 Create, select, and apply appropriate techniques, resources, and modern engineering and
IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6 Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
legal and cultural issues, and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8 Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO9 Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
PO10 Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO11 Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12 Recognize the need for and have the preparation and ability to engage in independent and
life-long learning in the broadest context of technological change.
Data Visualization With Python Laboratory BCS358D
Course Code BCS358D Sem III
CIE Marks 50 No of contact hours/week 0:0:2
Total Number of Lab Contact hrs 24 SEE Marks 50
Exam ccontact
Hours Duration 3 hrs Credits 1
PROGRAM -1
a) Write a python program to find the best of two test average marks out of three test’s marks
accepted from the user.
b) Develop a Python program to check whether a given number is palindrome or not and also
count the number of occurrences of each digit in the input number.
PROGRAM -2
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error message if
the condition for input value is not followed.
b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
PROGRAM -3
a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters, and lowercase letters.
b) Write a Python program to find the string similarity between two given strings.
PROGRAM -4
a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
PROGRAM -5
a) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
PROGRAM -6
a) Write a Python program to illustrate Linear Plotting using Matplotlib.
b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib.
PROGRAM -7
Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.
PROGRAM -8
a) Write a Python program to explain working with bokeh line graph using Annotations and
Legends.
b) Write a Python program for plotting different types of plots using Bokeh.
PROGRAM -9
a) Write a Python program to draw 3D Plots using Plotly Libraries.
PROGRAM -10
a) Write a Python program to draw Time Series using Plotly Libraries.
b) Write a Python program for creating Maps using Plotly Libraries.
Lesson plan
Data Visualization With Python Laboratory BCS358D
Pre-requisites:
Knowledge about Python Programming Language.
Learning Objectives:
CLO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications
CLO 2. Using Python programming language to develop programs for solving real-
world problems.
CLO 3. Implementation of Matplotlib for drawing different Plots
CLO 4. Demonstrate working with Seaborn, Bokeh for visualization.
CLO 5. Working with Plotly for 3D, Time Series and Maps.
Course Outcomes:
CO.NO. COURSE OUTCOMES BLL
Demonstrate the use of IDLE or Pycharm IDE to create applications using
C208.1 L3
python.
Apply python programming constructs to develop programs for solving
C208.2 L4
real-world problems.
Demonstrate the functionality of Matplotlib for generating various types
C208.3 L3
of plots.
C208.4 Demonstrate working with Seaborn, Bokeh for visualization. L2
Demonstrate the functionality of Plotly for 3D, Time Series and Maps for
C208.5 L2
visualization of data.
Sl. Program CO Mate
No rial
Lab Cycle Programs
a) Write a python program to find the best of two test average marks out of three test’s
marks accepted from the user. CO1,
1 CO2 TB1
b) Develop a Python program to check whether a given number is palindrome or not
and also count the number of occurrences of each digit in the input number.
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts
a value for N (where N >0) as input and pass this value to the function. Display suitable CO1,
2 error message if the condition for input value is not followed. CO2 TB1
b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
a) Write a Python program that accepts a sentence and find the number of words, digits, CO1,
3 uppercase letters, and lowercase letters. CO2 TB1
b) Write a Python program to find the string similarity between two given strings.
a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib. CO1,
4 b) Write a Python program to Demonstrate how to Draw a Scatter Plot using CO3 TB4
Matplotlib.
a) Write a Python program to Demonstrate how to Draw a Histogram Plot using
CO1, TB4
5 Matplotlib.
CO3
b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
a) Write a Python program to illustrate Linear Plotting using Matplotlib.
CO1, TB4
6 b) Write a Python program to illustrate liner plotting with line formatting using
CO3
Matplotlib.
Write a Python program which explains uses of customizing seaborn plots with CO1, TB4
7
Aesthetic functions. CO4
a) Write a Python program to explain working with bokeh line graph using
CO1, TB4
8 Annotations and Legends.
CO4
b) Write a Python program for plotting different types of plots using Bokeh.
a) Write a Python program to draw 3D Plots using Plotly Libraries. CO1, TB4
9
CO5
a) Write a Python program to draw Time Series using Plotly Libraries. CO1, TB4
10
b) Write a Python program for creating Maps using Plotly Libraries. CO5
Text Books
Sl.No Book Type Code Author/Title/Publishers
Al Sweigart, “Automate the Boring Stuff with
1. Text Book TB1
Python”,1stEdition, No Starch Press, 2015. (Available under CC-
BY-NC-SA license at https://automatetheboringstuff.com/)
2. Text Book TB2 Reema Thareja “Python Programming Using Problem Solving
Approach” Oxford University Press.
Allen B. Downey, “Think Python: How to Think Like a
3. Text Book TB3 Computer Scientist”, 2nd Edition, Green Tea Press, 2015.
(Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf)
4. Text Book TB4 Jake VanderPlas “Python Data Science Handbook” 1st Edition, O’REILLY.
CONTINUOUS EVALUATION PROCEDURE
Each program/Experiment = Total = 30m
(Viva=10m,Record/observation=5+5m, conduction= 10m)
Sl. USN Student Program1/1A/1 Program2 Program 3 Program Average
No. Name n
E V R T E V R T
Internal Assessment Marks= 20m
CONTENTS
Sl.No. Programs Page NO.
a) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
1. 10
b) Develop a Python program to check whether a given number is palindrome or
not and also count the number of occurrences of each digit in the input number.
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which
accepts a value for N (where N >0) as input and pass this value to the function.
2. Display suitable error message if the condition for input value is not followed. 12
b) Develop a python program to convert binary to decimal, octal to hexadecimal
using functions.
a) Write a Python program that accepts a sentence and find the number of words,
3. digits, uppercase letters, and lowercase letters. 14
b) Write a Python program to find the string similarity between two given strings.
a) Write a Python program to Demonstrate how to Draw a Bar Plot using
Matplotlib.
4. 16
b) Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.
a) Write a Python program to Demonstrate how to Draw a Histogram Plot using
Matplotlib.
5. 18
b) Write a Python program to Demonstrate how to Draw a Pie Chart using
Matplotlib.
a) Write a Python program to illustrate Linear Plotting using Matplotlib.
6. b) Write a Python program to illustrate liner plotting with line formatting using 20
Matplotlib.
Write a Python program which explains uses of customizing seaborn plots with
7. 22
Aesthetic functions.
c) Write a Python program to explain working with bokeh line graph using
8. Annotations and Legends. 24
Write a Python program for plotting different types of plots using Bokeh.
9. a) Write a Python program to draw 3D Plots using Plotly Libraries. 28
a) Write a Python program to draw Time Series using Plotly Libraries.
10. 29
b) Write a Python program for creating Maps using Plotly Libraries.
11. Extra Programs 31
12. Viva Questions 34
Data Visualization with Python Lab Manual BCS358D
PROGRAM -1
1a) Write a Python program to find the best of two test average marks
out of three test marks accepted by the user.
m1 = int(input("Enter marks for test1 : "))
m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))
if m1 <= m2 and m1 <= m3:
avgMarks = (m2+m3)/2
elif m2 <= m1 and m2 <= m3:
avgMarks = (m1+m3)/2
elif m3 <= m1 and m2 <= m2:
avgMarks = (m1+m2)/2
print("Average of best two test marks out of three test’s marks is",
avgMarks);
OUTPUT
Enter marks for test1: 45
Enter marks for test2: 39
Enter marks for test3: 48
Average of best two test marks out of three test’s marks is 46.5
Dept. of ISE, JSSATEB 10
Data Visualization with Python Lab Manual BCS358D
1b) Develop a Python program to check whether a given number is
palindrome or not and also count the number of occurrences of each
digit in the input number.
val = int(input("Enter a value : "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");
OUTPUT:
Enter a value: 1234234
Not Palindrome
1 appears 1 times
2 appears 2 times
3 appears 2 times
4 appears 2 times
Enter a value: 12321
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 1 times
Dept. of ISE, JSSATEB 11
Data Visualization with Python Lab Manual BCS358D
PROGRAM -2
2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program
that accepts a value for N (where N >0) as input and pass this value to
the function. Display a suitable error message if the condition for input
value is not followed.
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
num = int(input("Enter a number : "))
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")
OUTPUT:
Enter a number : 5
fn(5) = 3
Dept. of ISE, JSSATEB 12
Data Visualization with Python Lab Manual BCS358D
2b) Develop a python program to convert binary to decimal, octal to
hexadecimal using functions.
def binary_to_decimal(binary):
decimal = 0
power = 0
while binary != 0:
last_digit = binary % 10
decimal += last_digit * (2 ** power)
binary //= 10
power += 1
return decimal
def octal_to_hexadecimal(octal):
decimal = 0
power = 0
while octal != 0:
last_digit = octal % 10
decimal += last_digit * (8 ** power)
octal //= 10
power += 1
hexadecimal = ""
hex_digits = "0123456789ABCDEF"
while decimal != 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16
return hexadecimal
# Binary to Decimal conversion
binary_number = input("Enter a binary number: ")
decimal_number = binary_to_decimal(int(binary_number))
print("Decimal equivalent:", decimal_number)
# Octal to Hexadecimal conversion
octal_number = input("Enter an octal number: ")
hexadecimal_number = octal_to_hexadecimal(int(octal_number))
print("Hexadecimal equivalent:", hexadecimal_number)
OUTPUT:
Enter a binary number : 10111001
185
Enter a octal number : 675
1BD
Dept. of ISE, JSSATEB 13
Data Visualization with Python Lab Manual BCS358D
PROGRAM -3
3a) Write a Python program that accepts a sentence and find the number
of words, digits, uppercase letters, and lowercase letters.
def analyze_sentence(sentence):
word_count = len(sentence.split())
digit_count = 0
uppercase_count = 0
lowercase_count = 0
for char in sentence:
if char.isdigit():
digit_count += 1
elif char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
return word_count, digit_count, uppercase_count, lowercase_count
user_sentence = input("Enter a sentence: ")
word_count, digit_count, uppercase_count, lowercase_count =
analyze_sentence(user_sentence)
print("Number of words:", word_count)
print("Number of digits:", digit_count)
print("Number of uppercase letters:", uppercase_count)
print("Number of lowercase letters:", lowercase_count)
OUTPUT:
Enter a sentence : Rama went to Devaraja market to pick 2 kgs of vegetable
This sentence has 11 words
This sentence has 1 digits 2 upper case letters 42 lower case letters
Dept. of ISE, JSSATEB 14
Data Visualization with Python Lab Manual BCS358D
3b) Write a Python program to find the string similarity between two
given strings.
str1 = input("Enter String 1 \n")
str2 = input("Enter String 2 \n")
if len(str2) < len(str1):
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt/long)
OUTPUT:
Enter String 1
Python Exercises
Enter String 2
Python Exercises
Similarity between two said strings:
1.0
Enter String 1
Python Exercises
Enter String 2
Python Exercise
Similarity between two said strings:
0.9375
Dept. of ISE, JSSATEB 15
Data Visualization with Python Lab Manual BCS358D
PROGRAM -4
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot
using Matplotlib.
import matplotlib.pyplot as plt
# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [25, 50, 75, 100]
# Create a bar plot
plt.bar(categories, values, color='blue')
# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')
# Show the plot
plt.show()
Output:
Dept. of ISE, JSSATEB 16
Data Visualization with Python Lab Manual BCS358D
4b) Write a Python program to Demonstrate how to Draw a Scatter Plot
using Matplotlib.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 15, 13, 17, 20, 22, 25, 30, 28, 35]
# Create a scatter plot
plt.scatter(x, y, color='blue', marker='o', label='Scatter Points', alpha=0.6)
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
# Show the plot
plt.legend()
plt.grid(True)
plt.show()
Output:
Dept. of ISE, JSSATEB 17
Data Visualization with Python Lab Manual BCS358D
Program -5
5 a) Write a Python program to Demonstrate how to Draw a Histogram
Plot using Matplotlib.
import matplotlib.pyplot as plt
# Sample data
data = [10, 15, 10, 20, 25, 30, 25, 30, 30, 35, 40, 45, 45, 45, 50]
# Create a histogram plot
plt.hist(data, bins=5, color='blue', edgecolor='black')
# Add labels and title
plt.xlabel('Value Bins')
plt.ylabel('Frequency')
plt.title('Histogram Plot Example')
# Show the plot
plt.grid(True)
plt.show()
Output:
Dept. of ISE, JSSATEB 18
Data Visualization with Python Lab Manual BCS358D
5 b) Write a Python program to Demonstrate how to Draw a Pie Chart
using Matplotlib.
import matplotlib.pyplot as plt
# Sample data
labels = ['Category A', 'Category B', 'Category C', 'Category D']
sizes = [30, 45, 15, 10]
colors = ['lightblue', 'lightcoral', 'lightgreen', 'lightsalmon']
explode = (0.1, 0, 0, 0) # Explode the first slice (Category A)
# Create a pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
# Add a title
plt.title('Pie Chart Example')
# Show the plot
plt.show()
Output:
Dept. of ISE, JSSATEB 19
Data Visualization with Python Lab Manual BCS358D
Program -6
6 a) Write a Python program to illustrate Linear Plotting using
Matplotlib.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a linear plot
plt.plot(x, y, marker='o', color='blue', linestyle='--')
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Linear Plot Example')
# Show the plot
plt.grid(True)
plt.show()
Output:
Dept. of ISE, JSSATEB 20
Data Visualization with Python Lab Manual BCS358D
6 b) Write a Python program to illustrate liner plotting with line
formatting using Matplotlib.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a linear plot with custom line formatting
plt.plot(x, y, marker='o', color='blue', linestyle='--', linewidth=2,
markersize=8, label='Line Example')
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Linear Plot with Line Formatting')
# Show a legend
plt.legend()
# Show the plot
plt.grid(True)
plt.show()
Output:
Dept. of ISE, JSSATEB 21
Data Visualization with Python Lab Manual BCS358D
Program -7
7) Write a Python program which explains uses of customizing seaborn
plots with Aesthetic functions.
import seaborn as sns
import matplotlib.pyplot as plt
# Load a built-in dataset from Seaborn
tips = sns.load_dataset("tips")
# Set Seaborn style and color palette
sns.set(style="whitegrid", palette="Set1")
# Create a customized scatter plot
plt.figure(figsize=(8, 6))
sns.scatterplot(x="total_bill", y="tip", data=tips, hue="time", style="sex",
s=100, palette="Set2")
plt.title("Customized Scatter Plot")
plt.xlabel("Total Bill")
plt.ylabel("Tip")
plt.legend(title="Time of Day")
plt.show()
# Create a customized histogram
plt.figure(figsize=(8, 6))
sns.histplot(tips["total_bill"], bins=20, kde=True, color="skyblue",
line_kws={"color": "red"})
plt.title("Customized Histogram")
plt.xlabel("Total Bill")
plt.ylabel("Frequency")
plt.grid(True)
plt.show()
# Create a customized box plot
plt.figure(figsize=(8, 6))
sns.boxplot(x="day", y="total_bill", data=tips, palette="husl")
plt.title("Customized Box Plot")
plt.xlabel("Day")
plt.ylabel("Total Bill")
plt.show()
Output:
Dept. of ISE, JSSATEB 22
Data Visualization with Python Lab Manual BCS358D
Dept. of ISE, JSSATEB 23
Data Visualization with Python Lab Manual BCS358D
Program -8
8 a) Write a Python program to explain working with bokeh line graph
using Annotations and Legends.
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, Label, LabelSet
from bokeh.io import output_file
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a Bokeh figure
p = figure(title="Line Graph with Annotations and Legends", x_axis_label='X-
axis', y_axis_label='Y-axis')
# Create a data source
source = ColumnDataSource(data={'x': x, 'y': y})
# Create a line plot
p.line('x', 'y', source=source, legend_label='Line Plot', line_color='blue',
line_width=2)
# Create annotations
label = Label(x=3, y=6, x_units='data', y_units='data', text='Annotation',
background_fill_color='lightgray', background_fill_alpha=0.7)
p.add_layout(label)
# Create legends
p.legend.title = 'Legend'
p.legend.label_text_font_size = '12pt'
p.legend.background_fill_alpha = 0.7
# Create a label set
labels = LabelSet(x='x', y='y', text='y', level='glyph', source=source,
text_baseline='middle',
text_align='center', text_font_size='12pt')
p.add_layout(labels)
# Output the plot to an HTML file
output_file('line_graph_with_annotations_and_legends.html')
# Show the plot
show(p)
Dept. of ISE, JSSATEB 24
Data Visualization with Python Lab Manual BCS358D
Output:
Dept. of ISE, JSSATEB 25
Data Visualization with Python Lab Manual BCS358D
8 b) Write a Python program for plotting different types of plots using
Bokeh.
from bokeh.plotting import figure, show, output_file
from math import pi
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a Bokeh figure
output_file("bokeh_plots.html")
# Create a line plot
p1 = figure(title="Line Plot", x_axis_label='X-axis', y_axis_label='Y-axis')
p1.line(x, y, line_color='blue', line_width=2)
# Create a scatter plot
p2 = figure(title="Scatter Plot", x_axis_label='X-axis', y_axis_label='Y-axis')
p2.circle(x, y, size=10, color='green', alpha=0.6)
# Sample data for bar plot
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [30, 45, 15, 10]
# Create a bar plot
p3 = figure(x_range=categories, title="Bar Plot", x_axis_label='Categories',
y_axis_label='Values')
p3.vbar(x=categories, top=values, width=0.5, color='orange')
# Sample data for a pie chart
data = {'Categories': ['Category A', 'Category B', 'Category C', 'Category D'],
'Values': [30, 45, 15, 10]}
angles = [pi/4, pi/2, pi, 1.5*pi]
# Create a pie chart
p4 = figure(title="Pie Chart")
p4.wedge(x=0, y=0, radius=0.4, start_angle=angles, end_angle=angles[1:] +
[2*pi],
line_color="white", fill_color=['red', 'green', 'blue', 'orange'],
legend_label="Categories",
source=data)
# Show the plots
show(p1)
show(p2)
show(p3)
show(p4)
Dept. of ISE, JSSATEB 26
Data Visualization with Python Lab Manual BCS358D
Output:
Dept. of ISE, JSSATEB 27
Data Visualization with Python Lab Manual BCS358D
Program -9
9) Write a Python program to draw 3D Plots using Plotly Libraries.
import plotly.graph_objects as go
import numpy as np
# Create a grid of x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
# Define a 3D function (e.g., a surface)
Z = np.sin(np.sqrt(X**2 + Y**2))
# Create a 3D surface plot using Plotly
fig = go.Figure(data=go.Surface(z=Z, x=x, y=y))
fig.update_layout(scene=dict(zaxis_title="Z-axis", yaxis_title="Y-axis",
xaxis_title="X-axis"),
title="3D Surface Plot")
# Show the plot
fig.show()
Output:
Dept. of ISE, JSSATEB 28
Data Visualization with Python Lab Manual BCS358D
Program-10
10 a) Write a Python program to draw Time Series using Plotly
Libraries.
import plotly.graph_objects as go
import pandas as pd
# Sample time series data
data = {
'Date': pd.date_range(start='2023-01-01', periods=30, freq='D'),
'Value': [10, 15, 12, 18, 22, 24, 30, 28, 35, 40, 45, 48, 52, 50, 60, 58, 65,
70, 75, 80, 78, 85, 90, 95, 100, 95, 105, 110, 115, 120]
}
df = pd.DataFrame(data)
# Create a time series line plot
fig = go.Figure(data=go.Scatter(x=df['Date'], y=df['Value'],
mode='lines+markers', name='Time Series'))
# Set axis labels and plot title
fig.update_layout(xaxis_title='Date', yaxis_title='Value', title='Time Series
Plot')
# Show the plot
fig.show()
Output:
Dept. of ISE, JSSATEB 29
Data Visualization with Python Lab Manual BCS358D
10 b) Write a Python program for creating Maps using Plotly Libraries.
import plotly.express as px
# Sample data
locations = ['New York', 'Los Angeles', 'Chicago', 'San Francisco']
latitudes = [40.7128, 34.0522, 41.8781, 37.7749]
longitudes = [-74.0060, -118.2437, -87.6298, -122.4194]
# Create a map
fig = px.scatter_geo(lat=latitudes, lon=longitudes, locationmode='USA-states',
text=locations)
# Customize the map
fig.update_geos(
projection_scale=10,
center=dict(lon=-95, lat=38),
visible=False,
showcoastlines=True,
coastlinecolor="RebeccaPurple",
showland=True,
landcolor="LightGreen",
showocean=True,
oceancolor="LightBlue",
showlakes=True,
lakecolor="LightBlue",
)
# Set map title
fig.update_layout(
title_text='Sample US Map',
title_x=0.5,
)
# Show the map
fig.show()
Output:
Dept. of ISE, JSSATEB 30
Data Visualization with Python Lab Manual BCS358D
EXTRA PROGRAMS
1. Program to Generate a Random Password
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password
password_length = 12 # You can change the length
random_password = generate_password(password_length)
print("Random Password:", random_password)
Output:
Random Password: lv9;7yF%|/EW
Dept. of ISE, JSSATEB 31
Data Visualization with Python Lab Manual BCS358D
2. Program with Legends
import matplotlib.pyplot as plt
# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values_set1 = [25, 50, 75, 100]
values_set2 = [35, 45, 60, 80]
# Create a bar plot for the first set of values
plt.bar(categories, values_set1, label='Set 1', color='blue')
# Create a bar plot for the second set of values
plt.bar(categories, values_set2, label='Set 2', color='green', alpha=0.6) # Use
alpha to make it slightly transparent
# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot with Legends')
# Add a legend
plt.legend()
# Show the plot
plt.show()
Output:
Dept. of ISE, JSSATEB 32
Data Visualization with Python Lab Manual BCS358D
3. Program to create a Histogram.
import matplotlib.pyplot as plt
data = [1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7]
plt.hist(data, bins=5, edgecolor='black')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram Example')
plt.show()
Output:
Dept. of ISE, JSSATEB 33
Data Visualization with Python Lab Manual BCS358D
VIVA Questions with Answers
1. What is Matplotlib, and why is it commonly used for data
visualization in Python?
Matplotlib is a Python library used for creating 2D and 3D plots and
visualizations. It is widely used for its flexibility, simplicity, and extensive
customization options.
2. How do you create a bar plot using Matplotlib, and what is its
primary purpose?
You can create a bar plot in Matplotlib using the bar function. A bar plot is
used to display and compare categorical data, often showing the distribution
of values in different categories.
3. What is a scatter plot, and why would you use it in data
visualization?
A scatter plot is a type of plot used to display individual data points as dots.
It is useful for visualizing the relationship between two continuous variables
and identifying patterns or correlations.
4. Explain the purpose of a line plot in data visualization, and how is
it created using Matplotlib?
A line plot is used to show the trend or progression of data over a continuous
domain. It is created in Matplotlib using the plot function, connecting data
points with lines.
5. Describe the primary purpose of a pie chart in data visualization.
How is it created using Matplotlib?
A pie chart is used to represent data proportions within a whole. In Matplotlib,
you can create a pie chart using the pie function.
6. What is GeoJSON, and why is it important in creating maps in
Plotly?
GeoJSON is a format for encoding geographic data structures. It's important
in Plotly for representing geographical boundaries and features when creating
maps.
7. Explain the purpose of a choropleth map in data visualization, and
how is it created using Plotly?
Dept. of ISE, JSSATEB 34
Data Visualization with Python Lab Manual BCS358D
A choropleth map is used to represent data values in different geographical
regions. In Plotly, it's created using px.choropleth by mapping data to
geographical features.
8. What is a ColumnDataSource, and how is it used in creating maps
with Bokeh?
ColumnDataSource is a data structure in Bokeh used to manage and share
data between different plots and visualizations. It allows for efficient data
management in Bokeh.
9. What is the purpose of a 3D surface plot, and how is it created using
Plotly?
A 3D surface plot is used to visualize 3D data, often showing the
relationship between two continuous variables and a response variable.
It's created using go.Surface in Plotly.
10. How do you create a 3D scatter plot using Plotly, and what kind of
data is it suitable for?
A 3D scatter plot in Plotly is created using go.Scatter3d. It is suitable for
visualizing the relationship between three continuous variables.
11. Explain the concept of a random password generator, and how is it
implemented in Python?
A random password generator is a program that generates a secure,
random password. In Python, it can be implemented by selecting random
characters from character sets and combining them to form a password.
12. What is a histogram, and how does it display data distribution?
A histogram is a graphical representation of the distribution of a dataset. It
divides the data into intervals (bins) and displays the frequency of data points
within each bin.
13. Explain the concept of sorting, and how is it applied to a list of
strings using Python?
Sorting is the process of arranging elements in a specific order. In Python, you
can sort a list of strings using the sorted() function.
14. What is the primary purpose of a pie chart, and when is it
appropriate to use one in data visualization?
Dept. of ISE, JSSATEB 35
Data Visualization with Python Lab Manual BCS358D
A pie chart is used to represent data proportions within a whole. It is
appropriate when you want to show the composition of a whole in terms of its
parts.
15. Describe the key features of Plotly Express and Plotly Graph
Objects for creating visualizations.
Plotly Express is a high-level API for creating interactive visualizations with
minimal code. Plotly Graph Objects provides more control and customization
for creating complex visualizations.
16. How does Bokeh differ from Matplotlib in terms of creating
visualizations in Python?
Bokeh and Matplotlib are both Python libraries for creating visualizations.
Bokeh is more focused on interactive, web-based visualizations, while
Matplotlib is primarily used for static visualizations.
17. Explain the purpose of using GeoJSON data when creating maps in
Plotly, and where can you obtain GeoJSON data?
GeoJSON data is used to represent geographic boundaries and features in
Plotly maps. You can obtain GeoJSON data from sources like Natural Earth,
GADM, and government websites.
18. What is the primary use of a 3D surface plot in data visualization,
and what type of data does it represent?
A 3D surface plot is used to visualize the relationship between two
continuous variables and a response variable in 3D. It represents data
where three variables interact.
19. Describe the difference between a line plot and a scatter plot in
data visualization.
A line plot connects data points with lines, often showing trends over a
continuous domain. A scatter plot displays individual data points as dots and
is used to explore relationships between variables.
20. How do you create a random password generator in Python, and
what are the key components of the generator?
A random password generator in Python can be created using random
character selection from sets of letters, digits, and special characters. Key
components include character sets and password length.
Dept. of ISE, JSSATEB 36
Data Visualization with Python Lab Manual BCS358D
21. What is a Choropleth map, and how is it used to visualize data on
geographical regions?
A Choropleth map is a thematic map that uses shading or patterns to
represent the values of a variable in different geographical regions. It's used
to visualize data distribution across geographic areas.
22. What is the primary use of a scatter plot in data visualization, and
how does it help in data analysis?
A scatter plot is used to display individual data points as dots, making it
useful for visualizing relationships between two continuous variables. It helps
in data analysis by revealing patterns, correlations, and outliers in the data.
23. What is the primary purpose of a histogram, and in what scenarios
is it commonly employed in data visualization?
A histogram is used to visualize the distribution of a dataset. It's employed
when you want to understand the frequency and shape of data distribution,
especially for continuous data. Histograms are commonly used in statistical
analysis and quality control.
24. Can you explain the role of a ColumnDataSource in creating maps
with Bokeh, and what benefits does it offer in data visualization?
A ColumnDataSource is used to manage and share data between different
plots and visualizations in Bokeh. It offers benefits such as efficient data
management, allowing data to be shared and updated dynamically across
multiple plots. It's particularly useful in creating interactive visualizations.
25. What are the key differences between Plotly Express and Plotly
Graph Objects in terms of creating visualizations in Python?
Plotly Express is a high-level API that provides a simpler and more user-
friendly way to create interactive visualizations with minimal code. Plotly
Graph Objects, on the other hand, offers greater control and customization
for creating complex and highly customized visualizations. Users can choose
the API that best suits their specific needs and skill level.
Dept. of ISE, JSSATEB 37