0% found this document useful (0 votes)
48 views

DataVisualizationUsingPython LAB MANUAL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

DataVisualizationUsingPython LAB MANUAL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

JAIN COLLEGE OF ENGINEERING, BELAGAVI

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


ACADEMIC YEAR 2023-24

LABORATORY MANUAL

SUBJECT: DATA VISUALIZATION WITH PYTHON

LABORATORY

SUB CODE: BCS358D


SEMESTER: III-2022 CBCS Scheme

Prepared By
Dr. Vidya Dandagi
Prof.Anusha Chogund

Approved By
Dr. Uttam Patil
HOD, CSE
INSTITUTIONAL MISSION AND VISION

Vision

To be a university as a resource of solutions to diverse challenges of society by nurturing


innovation, research & entrepreneurship through value based education

Mission

• To provide work culture that facilitates effective teaching-learning process and lifelong
learning skills
• To promote innovation, collaboration and leadership through best practices
• To foster industry-institute interaction resulting in entrepreneurship skills and employment
opportunities
Department of Computer Science & Engineering

Vision

To create a centre of excellence in teaching, learning and professional environment in the


discipline of Computer Science and Engineering addressing emerging and existing challenges
striving to meet the requirement of both industry and society.

Mission

➢ To provide value-based quality technical education and training with continuous


improvement in the discipline of Computer Science and Engineering.
➢ To develop professionals to meet the requirements of industry and society.
➢ To promote innovation, dedication, and hard work with ethically and professionally
responsible behaviour.

Program Outcomes (POs)

Engineering Graduates will be able to:

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2. Problem analysis: 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/development of solutions: 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. Conduct investigations of complex problems: 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. Modern tool usage: 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. The engineer and society: 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. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

PO10. Communication: 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. Project management and finance: 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. Life-long learning: 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.

Program Specific Outcomes (PSOs)

PSO1: Apply mathematical and scientific skills in the area of computer science and engineering to
design, develop, analyze software and hardware based systems.

PSO2: Provide solutions using networking and database administration skills, and address the needs
of environmental and societal issues through entrepreneurial practices.

Program Educational Objectives (PEOs):

1. To produce graduates who have a strong foundation of knowledge and Engineering skills
that will enable them to have successful career in the field of computer science and
engineering.

2. To expose graduates to professional and team building skills along with ideas of innovation
and invention.

3. To prepare graduates with an ethics, social responsibilities, and professional concerns.


Data Visualization with Python
Semester III Examination type (SEE) Practical

Course Code BCS358D CIE Marks 50


Teaching Hours/Week (L:T:P: S) 0: 0: 2: 0 SEE Marks 50

Credits- 01 Exam Hours 100

Course 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.
CLO 5. Working with Plotly for 3D, Time Series and Maps.

Experiments

List of problems for which student should develop program and execute in the
Laboratory

1 a) Write a python program to find the best of two test average marks out of three test’s marks
acceptedfrom 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.

Datatypes:
https://www.youtube.com/watch?v=gCCVsvgR2KU
Operators:
https://www.youtube.com/watch?v=v5MR5JnKcZI Flow
Control:
https://www.youtube.com/watch?v=PqFKRqpHrjw For
loop: https://www.youtube.com/watch?v=0ZvaDa8eT5s
While loop:
https://www.youtube.com/watch?v=HZARImviDxg
Exceptions:
https://www.youtube.com/watch?v=6SPDvPK38tw

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
conditionfor input value is not followed.
b) Develop a python program to convert binary to decimal, octal to hexadecimal
using functions. Functions:https://www.youtube.com/watch?v=BVfCWuca9nw
Arguments:https://www.youtube.com/watch?v=ijXMGpoMkhQ
Return value: https://www.youtube.com/watch?v=nuNXiEDnM44

3 a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercaseletters and lowercase letters.
b) Write a Python program to find the string similarity between two given strings
Sample Output: Sample Output:
Original string: Original string:
Python Exercises Python
Exercises Python Exercises
Python Exercise
Similarity between two said strings: Similarity between two said strings:1.0
0.967741935483871
Strings: https://www.youtube.com/watch?v=lSItwlnF0eU
String functions: https://www.youtube.com/watch?v=9a3CxJyTq00

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.
https://www.youtube.com/watch?v=RRHQ6Fs1b8w&list=PLjVLYmrlmjGcC0B_FP3bkJJ
IPkV5GuZR & index=3
https://www.youtube.com/watch?v=7ABCuhWO9II&list=PLjVLYmrlmjGcC0B_FP3bkJJI
PkV5GuZR& index=4
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.
https://www.youtube.com/watch?v=Qk7caotaQUQ&list=PLjVLYmrlmjGcC0B_FP3bkJJIP
kV5GuZR&i ndex=6
https://www.youtube.com/watch?v=PSji21jUNO0&list=PLjVLYmrlmjGcC0B_FP3bkJJIPk
V5GuZR&in dex=7

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. https://www.youtube.com/watch?v=UO98lJQ3QGI&list=PL-
osiE80TeTvipOqomVEeZ1HRrcEvtZB_

7 Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.https://www.youtube.com/watch?v=6GUZXDef2U0

8 Write a Python program to explain working with bokeh line graph using Annotations and Legends.
a) Write a Python program for plotting different types of plots using
Bokeh.https://www.youtube.com/watch?v=HDvxYoRadcA

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


https://www.youtube.com/watch?v=cCck7hCanpw&list=PLE50dh6JzC4onXqkv9H3HtPbBVA8M94&i
ndex=4

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


b) Write a Python program for creating Maps using Plotly Libraries.
https://www.youtube.com/watch?v=xnJ2TNrGYik&list=PLE50h6JzC4onXqkv9H3HtPbBVA8M94&ind
ex=5
https://www.youtube.com/watch?v=D35m2CdMhVs&list=PLE50dh6JzC4onXqkv9H3HtPbBVA8M94
&index=6

Python (Full Course): https://www.youtube.com/watch?v=_uQrJ0TkZlc

Pedagogy For the above experiments the following pedagogy can be


considered. Problem based learning, Active learning, MOOC, Chalk &Talk

Course outcomes (Course Skill Set):


At the end of the course the student will be able to:
CO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications
CO 2. Use Python programming constructs to develop programs for solving real-
world problems CO 3. Use Matplotlib for drawing different Plots
CO 4. Demonstrate working with Seaborn, Bokeh for visualization.
CO 5. Use Plotly for drawing Time Series and Maps.

Assessment Details (both CIE and SEE)


The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End
Exam (SEE) is 50%. The minimum passing mark for the CIE is 40% of the maximum
marks (20 marks out of 50) and for the SEE minimum passing mark is 35% of the
maximum marks (18 out of 50 marks). A student shall be deemed to have satisfied
the academic requirements and earned the credits allotted to each subject/ course if
the student secures a minimum of 40% (40 marks out of 100) in the sum total of the
CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken
together.,
Continuous Internal Evaluation (CIE):
CIE marks for the practical course are 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
● Each experiment is to be evaluated for conduction with an observation sheet and record write-
up. Rubrics for the evaluation of the journal/write-up for hardware/software experiments are
designed by the faculty who is handling the laboratory session and are made known to students at
the beginning of the practical session.
● Record should contain all the specified experiments in the syllabus and each experiment write-
up will be evaluated for 10 marks.
● Total marks scored by the students are scaled down to 30 marks (60% of maximum
marks).
● Weightage to be given for neatness and submission of record/write-up on time.
● Department shall conduct a test of 100 marks after the completion of all the experiments listed in
the syllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and procedural
knowledge will carry a weightage of 60% and the rest 40% for viva-voce.
● The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
● The marks scored shall be scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and marks
of a test is the total CIE marks scored by the student.

Semester End Evaluation (SEE):


SEE marks for the practical course are 50 Marks.
SEE shall be conducted jointly by the two examiners of the same institute, examiners
are appointed by the Head of the Institute. The examination schedule and names of
examiners are informed to the university before the conduction of the examination.
These practical examinations are to be conducted between the schedule mentioned in
the academic calendar of the University. All laboratory experiments are to be
included for practical examination. (Rubrics) Breakup of marks and the instructions
printed on the cover page of the answer script to be strictly adhered to by the
examiners.
OR based on the course requirement evaluation rubrics shall be decided jointly by
examiners. Students can pick one question (experiment) from the questions lot
prepared by the examiners jointly. Evaluation of test write-up/ conduction procedure
and result/viva will be conducted jointly by examiners.

General rubrics suggested for SEE are mentioned here, writeup-20%,


Conduction procedure and result in -60%, Viva-voce 20% of maximum
marks. SEE for practical shall be evaluated for 100 marks and scored marks
shall be scaled down to 50 marks (however, based on course type, rubrics
shall be decided by the examiners)
Change of experiment is allowed only once and 15% of Marks allotted to
the procedure part are to be made zero.
The minimum duration of SEE is 02 hours
● Weightage of marks for PART A is 80% and for PART B is 20%. General
rubrics suggested to be followed for part A and part B.
● Change of experiment is allowed only once and Marks allotted to the procedure part to be made
zero (Not allowed for Part B).
● The duration of SEE is 03 hours
Rubrics suggested in Annexure-II of Regulation book
Textbooks:

1. Al Sweigart, “Automate the Boring Stuff with Python”,1stEdition, No


Starch Press, 2015. (Available under CC-BY-NC-SA license at
https://automatetheboringstuff.com/)
2. Reema Thareja “Python Programming Using Problem Solving Approach” Oxford University
Press.
3. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”,2nd
Edition, Green Tea Press, 2015. (Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf)
4. Jake VanderPlas “Python Data Science Handbook” 1st Edition, O’REILLY.
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.

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 : 87

Enter marks for test2 : 98

Enter marks for test3 : 67

Average of best two test marks out of three test’s marks is 92.5

Description:

The provided Python program is designed to calculate the average of the best two test marks out of
three. The user is prompted to input the marks for three tests (test1, test2, and test3). The program
then identifies the two highest test marks using the sorted function in descending order and selects the
top two values. Finally, it calculates the average of these two highest marks and prints the result. This
code is a concise way to determine the average performance based on the two best test scores out of
three.
1 b) Develop a Python program to check whether a given number is palindrome or not and also count
the number of occurrences of each digit in the input number.

Program:

str_val = input("Enter a value : ")

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

print("Palindrome")

else:

print("Not a Palindrome")

for i in range(10):

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

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

Output:

1) Enter a value : 12344321

Palindrome

1 appears 2 times

2 appears 2 times

3 appears 2 times

4 appears 2 times

2) Enter a value : 45678654

Not a Palindrome

4 appears 2 times

5 appears 2 times

6 appears 2 times

7 appears 1 times

8 appears 1 times
The provided Python script is a versatile program that performs two key tasks: palindrome checking and
character counting.

Palindrome Check:

The user is prompted to input a value.

The script determines whether the entered value is a palindrome, meaning it reads the same backward
as forward.

If the input is a palindrome, it prints “Palindrome”; otherwise, it prints “Not Palindrome.”

Character Count:

The script utilizes the Counter class from the collections module to efficiently count the occurrences of
each character in the input string.

It then sorts the keys of the counted dictionary and prints each character along with the number of
times it appears.

Alternate Character Count (commented-out):

The script provides an alternative method using a loop to count the occurrences of each digit (0 to 9) in
the input string.

This script is not only a quick and effective way to check for palindromes but also serves as a handy tool
for analyzing the frequency of characters in a given input. The inclusion of alternative methods
showcases the flexibility of the script, making it a valuable resource for both palindrome detection and
character frequency analysis.
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.

Program:

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))

else:

print("Error in input")

Output:

1) Enter a number : 8

fn( 8 ) = 13

2) Enter a number : -1

Error in input

Description:

The provided Python script introduces a recursive implementation to calculate terms in the
Fibonacci sequence. Here’s a concise overview:

Recursive Fibonacci Function:

The script defines a function fn that calculates the nth term in the Fibonacci sequence.
If the input n is 1 or 2, the function returns n - 1.

For n greater than 2, the function recursively calls itself with n-1 and n-2 and returns the sum of the
results.

User Input and Output:

The user is prompted to enter a number.

If a positive integer is provided, the script prints the result of calling the fn function with that
number, representing the nth term in the Fibonacci sequence.

If the entered value is not a positive integer, it prompts the user to enter a value greater than 0.

If a non-numeric value is entered, it catches the ValueError and suggests trying with a numeric
value.

This script serves as a simple yet illustrative example of a recursive function for computing Fibonacci
sequence terms, offering insights into recursive algorithms and user input handling in Python.
2 b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.

Program:

def bin2Dec(val):

rev = val[::-1]

dec = 0

i=0

for dig in rev:

dec += int(dig) * 2 ** i

i += 1

return dec

def oct2Hex(val):

rev = val[::-1]

dec = 0

i=0

for dig in rev:

dec += int(dig) * 8 ** i

i += 1

list = []

while dec != 0:

list.append(dec % 16)

dec = dec // 16

nl = []

for elem in list[::-1]:


if elem <= 9:

nl.append(str(elem))

else:

nl.append(chr(ord('A') + (elem - 10)))

hex = "".join(nl)

return hex

num1 = input("Enter a binary number : ")

print(bin2Dec(num1))

num2 = input("Enter a octal number : ")

print(oct2Hex(num2))

Output:

Enter a binary number : 1110

14

Enter a octal number : 675

1BD

Description:

This Python script includes two functions bin2Dec and oct2Hex for converting binary to decimal and
octal to hexadecimal, respectively. The script takes user input for binary and octal numbers and
converts them using these functions. Here’s a brief description:

Conversion Functions:

The bin2Dec function converts a binary number to decimal using the int() function with base 2.

The oct2Hex function converts an octal number to hexadecimal using the int() function with base 8.

User Input Handling:

The script includes try-except blocks to catch ValueError in case of invalid input.

It prompts the user for a binary and an octal number, converts them, and prints the results.

If an invalid input is detected, it prints an error message.


3 a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.

Program:

sentence = input("Enter a sentence : ")

wordList = sentence.split(" ")

print("This sentence has", len(wordList), "words")

digCnt = upCnt = loCnt = 0

for ch in sentence:

if '0' <= ch <= '9':

digCnt += 1

elif 'A' <= ch <= 'Z':

upCnt += 1

elif 'a' <= ch <= 'z':

loCnt += 1

print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt, "lower case letters")

Output:

Enter a sentence : The earth has 7 continents namely Asia, Africa, North America, South America,
Europe, Australia and Antarctica

This sentence has 16 words

This sentence has 1 digits 10 upper case letters 79 lower case letters

Description:

The above Python program is designed to analyse a user-inputted sentence, providing information
on the number of words, digits, uppercase letters, and lowercase letters in the given text. Here’s a
concise overview:

Word Count:

The script splits the input sentence into words and prints the count of words in the sentence.

Character Analysis:
It then iterates through each character in the sentence.

The script counts the number of digits, uppercase letters, and lowercase letters using the string
module.

Print Results:

Finally, it prints the counts of digits, uppercase letters, and lowercase letters in the given sentence.

This script serves as a versatile tool for quickly extracting key statistics from a user-provided
sentence, offering insights into the composition of the text in terms of words and character types.
3 b) Write a Python program to find the string similarity between two given strings.

Program:

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)*100)

Output:

Enter String 1:

Iceberg

Enter String 2:

Icecream

Similarity between two said strings:

37.5

Description:

The provided Python script is designed to compare the similarity between two user-inputted strings.
The user is prompted to input two strings, and the script, after converting them to lowercase for
case-insensitive comparison, calculates the similarity by counting the matching characters at
corresponding positions. The similarity is then expressed as a ratio relative to the length of the
longer string. Here’s a brief overview:

User Input:

The script prompts the user to enter two strings.

String Comparison:

The script then iterates through characters at corresponding positions and counts the matches.

Similarity Ratio:

The similarity between the two strings is calculated as the ratio of the count of matching characters
to the length of the longer string.

Alternative Solution :

The script includes an alternative solution using the SequenceMatcher class from the difflib library,
demonstrating a different approach to calculating string similarity.

This script offers a straightforward way to measure the similarity between two strings and presents
an alternative solution using Python libraries for a comparative understanding. It’s a useful tool for
users interested in comparing the likeness of textual data.
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.

import matplotlib.pyplot as plt

categories = ['0-10', '10-20', '20-30', '30-40', '40-50']

values = [55, 48, 25, 68, 90]

# Create a bar plot

plt.bar(categories, values, color='skyblue')

# Add labels and title

plt.xlabel('Overs')

plt.ylabel('Runs')

plt.title('Bar Plot Showing Runs scored in an ODI Match')

# Display the plot

plt.show()

Output:
Description:

The provided Python script utilizes the matplotlib library to create a bar plot showcasing runs scored
in an ODI (One Day International) cricket match. Here’s a concise overview:

Sample Data:

The script uses sample data representing runs scored in specific overs during an ODI cricket match.

Matplotlib Plotting:

It utilizes the matplotlib.pyplot module to create a bar plot.

The bar function is used to plot the data, where categories represent overs, and values represent
runs scored.

Labels and Title:

The script adds labels to the x-axis (Overs) and y-axis (Runs).

It includes a title, ‘Bar Plot Showing Runs scored in an ODI Match,’ to provide context to the plot.

Display:

The show function is called to display the generated bar plot.

This script is a straightforward example of using matplotlib to visualize data in a bar plot. It’s a
valuable resource for individuals interested in creating basic data visualizations, particularly in the
context of cricket statistics.
4 b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.

import matplotlib.pyplot as plt

import numpy as np

# BRICS nations data (hypothetical)

countries = ['Brazil', 'Russia', 'India', 'China', 'South Africa']

population = [213993437, 145912025, 1393409038, 1444216107, 61608912] # Population in 2021

per_capita_income = [9600, 11600, 2300, 11000, 6500] # Per capita income in USD

# Scale the population for circle size

circle_size = [pop / 1000000 for pop in population] # Scaling down for better visualization

# Assign different colors based on index

colors = np.arange(len(countries))

# Create a scatter plot with varying circle sizes and colors

scatter = plt.scatter(population, per_capita_income, s=circle_size, c=colors, cmap='viridis',


alpha=0.7, label='BRICS Nations')

# Annotate each point with the country name

for i, country in enumerate(countries):

plt.annotate(country, (population[i], per_capita_income[i]), textcoords="offset points",


xytext=(0,5), ha='center')

# Add colorbar

plt.colorbar(scatter, label='Index')

# Add labels and title

plt.xlabel('Population')

plt.ylabel('Per Capita Income (USD)')

plt.title('Population vs Per Capita Income of BRICS Nations')

# Display the plot

plt.show()
Output:

Description:

The provided Python script employs the matplotlib library, along with numpy, to create a scatter
plot visualizing population against per capita income for BRICS nations. Here’s a concise overview:

Sample Data:

The script uses hypothetical data for BRICS nations, including population and per capita income.

Scaling for Visualization:

Circle sizes are scaled down from population values to enhance visualization.

Color Assignment:

Different colors are assigned based on the index of each country.

Scatter Plot:

The scatter function is used to create a scatter plot with varying circle sizes and colors.

Annotations:

Each point on the plot is annotated with the country name for clarity.

Colorbar:
A colorbar is added to the plot, providing a reference for the color index.

Labels and Title:

Labels for the x-axis, y-axis, and a title are included to provide context.

Display:

The show function is called to display the generated scatter plot.

This script serves as an excellent example of using matplotlib for creating informative and visually
appealing scatter plots, especially for comparing socio-economic indicators among different
countries. It can be helpful for readers interested in data visualization and analysis.
5 b) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib

import matplotlib.pyplot as plt

import numpy as np

# Generate random student scores (example data)

np.random.seed(42)

student_scores = np.random.normal(loc=70, scale=15, size=100)

# Create a histogram plot

plt.hist(student_scores, bins=20, color='skyblue', edgecolor='black')

# Add labels and title

plt.xlabel('Student Scores')

plt.ylabel('Frequency')

plt.title('Distribution of Student Scores')

# Display the plot

plt.show()

Output:
Description:

The provided Python script utilizes the matplotlib library and numpy to generate a histogram plot
illustrating the distribution of student scores. Here’s a concise overview:

Random Data Generation:

The script generates example data representing student scores using a normal distribution
(np.random.normal).

Histogram Plot:

It creates a histogram plot using the hist function, where student_scores is the data array, bins
determines the number of bins, and color sets the fill color while edgecolor sets the color of bin
edges.

Labels and Title:

The script adds labels to the x-axis (Student Scores) and y-axis (Frequency).

A title, ‘Distribution of Student Scores,’ is included to provide context to the plot.

Display:

The show function is called to display the generated histogram plot.

This script serves as a simple yet effective demonstration of using matplotlib to visualize the
distribution of a dataset, making it suitable for readers interested in introductory data visualization
techniques. It’s especially valuable for those learning to interpret histograms in the context of
student scores or similar datasets.
5 b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.

import matplotlib.pyplot as plt

#Number of FIFA World Cup wins for different countries

countries = ['Brazil', 'Germany', 'Italy', 'Argentina', 'Uruguay', 'France', 'England', 'Spain']

wins = [5, 4, 4, 3, 2, 2, 1, 1] # Replace with actual data

# Colors for each country

colors = ['yellow', 'magenta', 'green', 'blue', 'lightblue', 'blue', 'red', 'cyan']

plt.pie(wins, labels=countries, autopct='%1.1f%%', colors=colors, startangle=90, explode=[0.2, 0.2,


0.2, 0.2, 0.2, 0.2, 0.2, 0.2], shadow=True)

# Add title

plt.title('FIFA World Cup Wins by Country')

# Display the plot

plt.axis('equal') # Equal aspect ratio ensures that the pie chart is circular.

plt.show()

Output:
Description:

The provided Python script utilizes the matplotlib library to create a visually appealing pie chart
representing the number of FIFA World Cup wins for different countries. Here’s a concise overview:

Data Representation:

The script uses hypothetical data representing the number of FIFA World Cup wins for different
countries.

Pie Chart Creation:

It creates a pie chart using the pie function, where wins is the data array, labels are country names,
and autopct formats the percentage display.

Colors and Styling:

Different colors are assigned to each country using the colors parameter.

The pie chart is enhanced with features such as a start angle, explode effect, and shadow.

Title:

The script adds a title to the pie chart, enhancing the overall context.

Display:

The show function is called to display the generated pie chart.

This script serves as a clear and concise example of using matplotlib to create visually engaging pie
charts, making it suitable for readers interested in representing categorical data, such as FIFA World
Cup wins, in a graphical format.
6 a) Write a Python program to illustrate Linear Plotting using Matplotlib.

import matplotlib.pyplot as plt

# Hypothetical data: Run rate in an T20 cricket match

overs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

runs_scored = [0,7,12,20,39,49,61,83,86,97,113,116,123,137,145,163,172,192,198,198,203]

# Create a linear plot

plt.plot(overs, runs_scored)

# Add labels and title

plt.xlabel('Overs')

plt.ylabel('Runs scored')

plt.title('Run scoring in an T20 Cricket Match')

# Display the plot

plt.grid(True)

plt.show()

Output:
Description:

The provided Python script utilizes the matplotlib library to create a linear plot representing the run
rate in a hypothetical T20 cricket match. Here’s a concise overview:

Hypothetical Data:

The script uses hypothetical data representing the number of runs scored in each over of a T20
cricket match.

Linear Plot:

It creates a linear plot using the plot function, where overs is on the x-axis and runs_scored is on the
y-axis.

Labels and Title:

The script adds labels to the x-axis (Overs) and y-axis (Runs scored).

A title, ‘Run Scoring in a T20 Cricket Match,’ provides context to the plot.

Grid:

The plot includes a grid for better readability.

Display:

The show function is called to display the generated linear plot.

This script serves as a straightforward example of using matplotlib to visualize run scoring trends in a
T20 cricket match, making it suitable for readers interested in representing time-dependent data in
a graphical format.
6 b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib.

import matplotlib.pyplot as plt

# Hypothetical data: Run rate in an T20 cricket match

overs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

runs_scored = [0,7,12,20,39,49,61,83,86,97,113,116,123,137,145,163,172,192,198,198,203]

# Create a linear plot

plt.plot(overs, runs_scored, marker='X', linestyle='dashed',color='red', linewidth=2,


markerfacecolor='blue', markersize=8)

# Add labels and title

plt.xlabel('Overs', color = 'green')

plt.ylabel('Runs scored')

plt.title('Run scoring in an T20 Cricket Match')

# Display the plot

plt.grid(True)

plt.show()

Output:
Description:

The provided Python script, an extension of the previous T20 cricket match run rate plot, customizes
the appearance of the plot with specific markers, line styles, colors, and label styles. Here’s a concise
overview:

Customized Plot Appearance:

The plot function is customized with parameters such as marker, linestyle, color, linewidth,
markerfacecolor, and markersize to control the appearance of the plot.

Labels and Title Styling:

The script adds labels to the x-axis (Overs) and y-axis (Runs scored) with specific color styling.

The title, ‘Run Scoring in a T20 Cricket Match,’ maintains clarity.

Grid:

The plot includes a grid for better readability.

Display:

The show function is called to display the generated customized linear plot.

This script is an excellent example for readers looking to customize plot aesthetics in matplotlib for a
more visually appealing representation of data. It’s especially helpful for those interested in
enhancing the clarity and style of their data visualizations.
7 ) Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.

import numpy as np

import matplotlib.pyplot as plt

import seaborn as sns

def sinplot(n=10):

x = np.linspace(0, 14, 100)

for i in range(1, n + 1):

plt.plot(x, np.sin(x + i * .5) * (n + 2 - i))

sns.set_theme()

#sns.set_context("talk")

sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})

sinplot()

plt.title('Seaborn plots with Aesthetic functions')

plt.show()

Output:
Description:

The provided Python script utilizes the seaborn library, in conjunction with numpy and matplotlib, to
create a series of sine wave plots with customized aesthetics. Here’s a concise overview:

Data Generation:

The script uses numpy to generate a series of sine wave plots.

Seaborn Integration:

seaborn is imported and configured with a default theme (set_theme).

The context is set to “notebook” with customized font scaling and line width (set_context).

Customized Aesthetics:

The sinplot function generates multiple sine wave plots with varying frequencies and amplitudes.

Title and Display:

The script adds a title to the plot, ‘Seaborn Plots with Aesthetic Functions.’

The show function is called to display the generated plots.

This script serves as an illustrative example of how seaborn can be used to enhance the aesthetics of
data visualizations, providing readers with insights into customizing plot styles and themes for more
visually appealing results. It’s particularly useful for those looking to leverage seaborn for improved
aesthetics in their data analysis and visualization workflows.
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.

import numpy as np

from bokeh.layouts import gridplot

from bokeh.plotting import figure, show

x = np.linspace(0, 4*np.pi, 100)

y = np.sin(x)

TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"

p1 = figure(title="Example 1", tools=TOOLS)

p1.circle(x, y, legend_label="sin(x)")

p1.circle(x, 2*y, legend_label="2*sin(x)", color="orange")

p1.circle(x, 3*y, legend_label="3*sin(x)", color="green")

p1.legend.title = 'Markers'

p2 = figure(title="Example 2", tools=TOOLS)

p2.circle(x, y, legend_label="sin(x)")

p2.line(x, y, legend_label="sin(x)")

p2.line(x, 2*y, legend_label="2*sin(x)",

line_dash=(4, 4), line_color="orange", line_width=2)

p2.square(x, 3*y, legend_label="3*sin(x)", fill_color=None, line_color="green")

p2.line(x, 3*y, legend_label="3*sin(x)", line_color="green")

p2.legend.title = 'Lines'

show(gridplot([p1, p2], ncols=2, width=400, height=400))


Output:
Description:

The provided Python script demonstrates the use of the Bokeh library to create interactive data
visualizations with multiple plots. Here’s a concise overview:

Data Generation:

The script generates example data (x and y) using NumPy to represent sine waves.

Interactive Tools:

Bokeh’s interactive tools (TOOLS) are enabled for features like pan, zoom, reset, and save.

Multiple Plots:

Two separate plots (p1 and p2) are created with different visualizations, including circles, lines, and
markers.

Legend and Titles:

Legends are added to distinguish between different elements in the plots.

Titles are provided for each plot.

Grid Layout:

The gridplot function is used to arrange the plots in a grid layout.

Interactive Display:

The show function is called to display the grid layout, enabling interactive exploration.

This script serves as an introduction to using Bokeh for creating interactive visualizations with
multiple plots, making it suitable for readers interested in interactive data exploration and
visualization techniques.
9) Write a Python program to draw 3D Plots using Plotly Libraries.

import plotly.graph_objects as go

import numpy as np

# Generate sample 3D data

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

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

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

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

# Create a 3D surface plot

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

# Customize layout

fig.update_layout(scene=dict(

xaxis_title='X Axis',

yaxis_title='Y Axis',

zaxis_title='Z Axis'),

margin=dict(l=0, r=0, b=0, t=40),

title='3D Surface Plot of sin(sqrt(x^2 + y^2))')

# Display the 3D surface plot

fig.show()

Description:

This program generates a 3D surface plot of the function z = sin(sqrt(x2+y2)). You can modify the
function or provide your own data to create different types of 3D plots. The visualization will be
interactive, allowing you to rotate and explore the plot.

In this Python program, we leverage the power of Plotly Express to visualize the economic evolution
of Asian countries over time. The dataset used is Gapminder, a comprehensive collection of global
development indicators. The focus is specifically on the Asian continent.

Import Libraries:
We start by importing the necessary libraries, including plotly.express for interactive visualizations.

Data Loading:

We load the Gapminder dataset and filter it to include only Asian countries.

3D Line Plot:

The key visualization is a 3D line plot created using px.line_3d.

The x-axis represents the GDP per capita (gdpPercap), the y-axis represents the population (pop),
and the z-axis represents the year (year).

Each line corresponds to a different country, differentiated by color.

Interactive Exploration:

The resulting plot is interactive, allowing users to zoom, pan, and hover over data points to explore
specific details.

Users can observe how GDP per capita and population have changed over the years for various
Asian countries. The color-coded lines help distinguish between different nations.

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

Program:

import pandas as pd

import plotly.express as px

dollar_conv = pd.read_csv('CUR_DLR_INR.csv')

fig = px.line(dollar_conv, x='DATE', y='RATE', title='Dollar vs Rupee')

fig.show()

Output:

Description:

The provided Python script showcases the use of the Plotly Express library to create an interactive
line plot depicting the exchange rate between the US Dollar and the Indian Rupee over time. Here’s
a concise overview:

Data Import:

The script uses the Pandas library to read currency conversion data from a CSV file
(‘CUR_DLR_INR.csv’). You can download the csv file given above.

Plotly Express:

Plotly Express (px) is employed to create an interactive line plot with the exchange rate data.

Line Plot:

The line function from Plotly Express is used to generate a line plot.
The x-axis represents dates (‘DATE’), and the y-axis represents exchange rates (‘RATE’).

Title:

The plot is given a title, ‘Dollar vs Rupee,’ for context.

Interactive Display:

The show method is called on the figure (fig) to display the interactive plot.

This script provides a quick and effective demonstration of using Plotly Express to visualize time-
series data, making it suitable for readers interested in creating interactive and visually appealing
line plots for financial or currency-related datasets.
10 b) Write a Python program for creating Maps using Plotly Libraries.

Program:

import json

import numpy as np

import pandas as pd

import plotly.express as px

#Uncomment below lines to render map on your browser

#import plotly.io as pio

#pio.renderers.default = 'browser'

india_states = json.load(open("states_india.geojson", "r"))

df = pd.read_csv("india_census.csv")

state_id_map = {}

for feature in india_states["features"]:

feature["id"] = feature["properties"]["state_code"]

state_id_map[feature["properties"]["st_nm"]] = feature["id"]

df = pd.read_csv("india_census.csv")

df["Density"] = df["Density[a]"].apply(lambda x: int(x.split("/")[0].replace(",", "")))

df["id"] = df["State or union territory"].apply(lambda x: state_id_map[x])

#print(df.head())

fig = px.choropleth(

df,

locations="id",

geojson=india_states,

color="Population",

hover_name="State or union territory",


hover_data=["Density", "Sex ratio", "Population"],

title="India Population Statewise",

fig.update_geos(fitbounds="locations", visible=False)

fig.show()

Output:

Description:

In this Python program, we leverage Plotly Express to create an insightful choropleth map that
visualizes key demographic indicators across states and union territories in India. The data is sourced
from India’s census, providing a comprehensive overview of population distribution, density, and
sex ratio.

Program Overview:

Import Libraries:

We begin by importing necessary libraries, including json for handling GeoJSON data, numpy for
numerical operations, pandas for data manipulation, and plotly.express for creating interactive
visualizations.

Load GeoJSON and Census Data:

The GeoJSON file representing Indian states is loaded, and census data is read from a CSV file
containing information about population, density, and sex ratio.

Data Preparation:
We create a mapping between state names and their corresponding IDs for seamless integration
with GeoJSON features.

Additional data preprocessing includes converting density values to integers and creating a unique
identifier (id) for each state.

Choropleth Map:

The choropleth map is generated using px.choropleth. Key parameters include:

locations: State IDs for mapping.

geojson: GeoJSON data for Indian states.

color: Population, determining color intensity on the map.

hover_name: State names for hover information.

hover_data: Additional information displayed on hover, including density, sex ratio, and population.

title: Title of the map.

Interactive Exploration:

The resulting choropleth map is interactive, allowing users to hover over states to explore
population demographics.

Users can explore and compare population distribution, density, and sex ratio across different states
and union territories in India. This program demonstrates the power of Plotly Express for creating
meaningful and interactive visualizations. The choropleth map provides valuable insights into the
demographic landscape of India.

You might also like