0% found this document useful (0 votes)
2 views16 pages

Python Lab Manual New

The document is a lab manual from SRI Sairam College of Engineering focused on Data Visualization with Python. It includes a list of experiments that cover various Python programming tasks related to data visualization using libraries such as Matplotlib, Seaborn, Plotly, and Bokeh. Additionally, it provides a brief overview of data visualization and examples of different visualization techniques.

Uploaded by

Senthilnathan S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Python Lab Manual New

The document is a lab manual from SRI Sairam College of Engineering focused on Data Visualization with Python. It includes a list of experiments that cover various Python programming tasks related to data visualization using libraries such as Matplotlib, Seaborn, Plotly, and Bokeh. Additionally, it provides a brief overview of data visualization and examples of different visualization techniques.

Uploaded by

Senthilnathan S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SRI SAIRAM COLLEGE OF ENGINEERING, ANEKAL, BENGALURU

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

DATA VISUALIZATION WITH PYTHON

BCS358D

LAB MANUAL
LIST OF EXPERIMENTS:

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.

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.

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.

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.

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.

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.

7. Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.

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.

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

10. a) Write a Python program to draw Time Series using Plotly Libraries.
b) Write a Python program for creating Maps using Plotly Libraries.
What is data visualization?
Data visualization is the graphical representation of information and data. Visualization transforms
data into images effectively and accurately represent information about the data. It is made for
easier interpretation of patterns and trends as opposed to looking at data in a tabular/spreadsheet
format.

Examples of Data Visualizations:

Python offers a wide range of libraries for data visualization, each suited for different types of
visualizations and use cases. Some of the most popular ones include:

1. Matplotlib

A foundational library for creating static, animated, and interactive visualizations in Python.
Matplotlib is a comprehensive library for creating static, animated and interactive visualizations in
Python.

● Usage: Matplotlib/Pandas is mostly used for quick plotting of Pandas DataFrames and time series
analysis. Matplotlib Seaborn Plotly Tableau Resources Matplotlib –

Pros and Cons of Matplotlib:

● Pro: Easy to setup and use.

● Pro: Very customizable.

● Con: Visual presentation tends to be simple compared to other tools.

Use cases: Line plots, bar charts, histograms, scatter plots, etc.

2.Seaborn

Built on top of Matplotlib, Seaborn simplifies complex visualizations with fewer lines
of code. It's great for statistical plots and has beautiful default styles.

Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level


interface for drawing attractive and informative statistical graphics.
● Usage: Those who want to create amplified data visuals, especially in color.

Pros and Cons:

● Pro: Includes higher level interfaces and settings than does Matplotlib

● Pro: Relatively simple to use, just like Matplotlib

. ● Pro: Easier to use when working with Dataframes.

● Con: Like Matplotlib, data visualization seems to be simpler than other tools.

 Use cases: Heatmaps, correlation matrices, pair plots, and distribution plots.

3. Plotly

A versatile library for creating interactive, web-based visualizations. It's highly


customizable and integrates with Jupyter notebooks.

 From website: Plotly is an interactive, open-source plotting library that supports over 40
unique chart types.
 Usage: Plotly is advantageous for those who want an interactive environment which many
use cases, ranging from statistics to finance to geography and more.

Pros and Cons of Plotly:

 Pro: Make beautiful, interactive, exportable figures in just a few lines of code. ● Pro: Much
more interactive & visually flexible than Matplotlib or Seaborn.
 Con: Confusing initial setup to use Plotly without an online account, and lots of code to
write.
 Con: Out-of-date documentation and the large range of Plotly tools (Chart Studio, Express,
etc.) make it hard to keep up.
 Use cases: 3D plots, interactive plots, geographic maps.

4. Bokeh

Another interactive visualization library, often used for building interactive web dashboards.

Bokeh is an interactive visualization Python library. ● Provides elegant and concise construction of
versatile graphics.

● Usage: Can be used in Jupyter Notebooks and can provide high-performance interactive charts and
plots.

 Use cases: Streaming plots, interactive dashboards, large datasets.

5. Altair

A declarative statistical visualization library that makes it easy to create interactive


plots by focusing on data transformations rather than the details of rendering.
 Use cases: Simple, interactive visualizations with minimal code.

6. ggplot (plotnine)

Based on R's popular ggplot2 library, plotnine allows you to create complex plots based on
a grammar of graphics.

 Use cases: Layered plots, aesthetic mappings, and statistical visualizations.


Experiments:
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 : "))
best_of_two = sorted([m1, m2, m3], reverse=True)[:2]
average_best_of_two = sum(best_of_two)/2
print("Average of best two test marks out of three test’s marks is", average_best_of_two);

Output:

b.Develop a Python program to check whether a given number is palindrome or not andalso
count the number of occurrences of each digit in the input number.

from collections import Counter


value = input("Enter a value : ")
if value == value[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
counted_dict = Counter(value)
for key in sorted(counted_dict.keys()):
print(f'{key} appears {counted_dict[key]} times');
Q2. 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.

def fn(n):
if n <= 2:
return n - 1
else:
return fn(n-1) + fn(n-2)
try:
num = int(input("Enter a number : "))
if num > 0:
print(f' fn({num}) = {fn(num)}')
else:
print("Input should be greater than 0")
except ValueError:
print("Try with numeric value")
Ouput:

b) Develop a python program to convert binary to decimal, octal to hexadecimal using


functions.

def bin2Dec(val):
return int(val, 2)
def oct2Hex(val):
return int(val, 8)
try:
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
except ValueError:
print("Invalid literal in input with base 2")
try:
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
except ValueError:
print("Invalid literal in input with base 8")

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

import string
sentence = input("Enter a sentence : ")
wordList = sentence.strip().split(" ")
print(f'This sentence has {len(wordList)} words', end='\n\n')
digit_count = uppercase_count = lowercase_count = 0
for character in sentence:
if character in string.digits:
digit_count += 1
elif character in string.ascii_uppercase:
uppercase_count += 1
elif character in string.ascii_lowercase:
lowercase_count += 1
print(f'This sentence has {digit_count} digits',
f' {uppercase_count} upper case letters',
f' {lowercase_count} lower case letters', sep='\n')
Output:

b) Write a Python program to find the string similarity between two given strings

from difflib import SequenceMatcher


str1 = input("Enter String 1 : ")
str2 = input("Enter String 2 : ")
sim = SequenceMatcher(None, str1, str2).ratio()
print("Similarity between strings \"" + str1 + "\" and \"" + str2 + "\" is : ",sim)

Output:

Q4. 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]
plt.bar(categories, values, color='skyblue')
plt.xlabel('Overs')
plt.ylabel('Runs')
plt.title('Bar Plot Showing Runs scored in an ODI Match')
plt.show()
Output:

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

Matplotlib.

import matplotlib.pyplot as plt


countries = ['Brazil', 'Russia', 'India', 'China', 'South Africa']
population = [213993437, 145912025, 1393409038, 1444216107, 61608912]
per_capita_income = [9600, 11600, 2300, 11000, 6500]
circle_size = [pop / 1000000 for pop in population]
colors = np.arange(len(countries))
scatter = plt.scatter(population, per_capita_income, s=circle_size, c=colors, cmap='viridis',
alpha=0.7, label='BRICS Nations')
for i, country in enumerate(countries):
plt.annotate(country, (population[i], per_capita_income[i]), textcoords="offset
points", xytext=(0,5), ha='center')

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

plt.xlabel('Population')

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


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

Q5. a) Write a Python program to Demonstrate how to Draw a Histogram Plot

using Matplotlib.

import matplotlib.pyplot as plt


import numpy as np
np.random.seed(42)
student_scores = np.random.normal(loc=70, scale=15, size=100)
plt.hist(student_scores, bins=20, color='skyblue', edgecolor='black')
plt.xlabel('Student Scores')
plt.ylabel('Frequency')
plt.title('Distribution of Student Scores')
plt.show()
Output :
b) Write a Python program to Demonstrate how to Draw a Pie Chart using

Matplotlib.

import matplotlib.pyplot as plt


countries = ['Brazil', 'Germany', 'Italy', 'Argentina', 'Uruguay', 'France', 'England','Spain']
wins = [5, 4, 4, 3, 2, 2, 1, 1]
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)
plt.title('FIFA World Cup Wins by Country')
plt.axis('equal') # Equal aspect ratio ensures that the pie chart is circular.
plt.show()

Output:

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

import matplotlib.pyplot as plt


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]
plt.plot(overs, runs_scored)
plt.xlabel('Overs')
plt.ylabel('Runs scored')
plt.title('Run scoring in an T20 Cricket Match')
plt.grid(True)
plt.show()
Output:

b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib.
import matplotlib.pyplot as plt
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]
plt.plot(overs, runs_scored, marker='X', linestyle='dashed',color='red', linewidth=2,
markerfacecolor='blue', markersize=8)
plt.xlabel('Overs', color = 'green')
plt.ylabel('Runs scored')
plt.title('Run scoring in an T20 Cricket Match')
plt.grid(True)
plt.show()
Output:
Q7. 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()
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sinplot()
plt.title('Seaborn plots with Aesthetic functions')
plt.show()
Output :
Q8. Write a Python program to explain working with bokeh line graph using
Annotations and Legends.
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, width=400, height=400)
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, width=400, height=400)
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))

Output:
Q9. Write a Python program to draw 3D Plots using Plotly Libraries
import plotly.graph_objects as go
import numpy as np
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))
fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])
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))')
fig.show()
Output:
Q10. a) Write a Python program to draw Time Series using Plotly Libraries.
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:

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


import plotly.express as px
import pandas as pd
data =
pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapmind
er_with_codes.csv')
fig = px.choropleth(data, locations='iso_alpha', color='gdpPercap',
hover_name='country',
projection='natural earth', title='GDP per Capita by Country')
fig.show()

OUTPUT:

You might also like