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

Manual

The document contains a list of lab programs for a Python programming course focused on data analytics. It includes various tasks such as calculating averages, checking for palindromes, generating Fibonacci sequences, and creating different types of plots using libraries like Matplotlib and Plotly. The document provides both programming tasks and example codes for each task.
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 views24 pages

Manual

The document contains a list of lab programs for a Python programming course focused on data analytics. It includes various tasks such as calculating averages, checking for palindromes, generating Fibonacci sequences, and creating different types of plots using libraries like Matplotlib and Plotly. The document provides both programming tasks and example codes for each task.
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/ 24

Department of Master of Computer Applications

Lab: Python Programming for Data Analytics Lab code: N3MC01

List of Lab Programs


Q-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.

Q-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.

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

Q-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.

Q-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.

Q-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.

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

Q-8) Write a Python program to draw 3D Plots using Plotly Libraries.

Q-9) Write a Python program to draw Time Series using Plotly Libraries.

Q-10) Write a Python program to draw Time Series using Plotly Libraries.
Q-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.
Code:

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:
Enter marks for test1 : 78
Enter marks for test2 : 89
Enter marks for test3 : 67
Average of best two test marks out of three test’s marks is 83.5

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.

Code:

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

Output:
Enter a value : 123321
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 2 times
Q-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.

Code:

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

Output:
Enter a number : 7 Enter a number : 6 Enter a number : 5
fn(7) = 8 fn(6) = 5 fn(5) = 3

Enter a number : -3 Enter a number : abc


Input should be greate Try with numeric value
r than 0

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

Code:
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")

Output:
Enter a binary number : 101010 Enter a binary number : 1001
42 9
Enter a octal number : 755 Enter a octal number : 954
493 Invalid literal in input with base 8

Enter a binary number : 0100 Enter a binary number : 0010


4 2
Enter a octal number : 751 Enter a octal number : 950
489 Invalid literal in input with base 8

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

Code:
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:
Enter a sentence : I want to tell you something today
This sentence has 7 words

This sentence has 0 digits


1 upper case letters
27 lower case letters
Enter a sentence : Python subject has 4 credits and SEE as 50 Marks
This sentence has 10 words

This sentence has 3 digits


5 upper case letters
31 lower case letters

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

Code:
str1 = input("Enter String 1 \n").lower()
str2 = input("Enter String 2 \n").lower()

string_1_length = len(str1)
string_2_length = len(str2)

short_string_length, long_string_length = min(string_1_length, string_2_length),


max(string_1_length, string_2_length)

match_count = 0
for i in range(short_string_length):
if str1[i] == str2[i]:
match_count += 1

print("Similarity between two said strings:")


print(match_count/long_string_length)

Output:
Enter String 1 Enter String 1
Sidda Sidda
Enter String 2 Enter String 2
Ganga Sidda
Similarity between two said strings: Similarity between two said strings:
0.2 1.0
Q-4)
a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.

Bar Plot using Matplotlib


Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
Python Code

import matplotlib.pyplot as plt

# Sample data for demonstration


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

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:
1. Sample Data:
• The script uses sample data representing runs scored in specific overs during an ODI
cricket match.
2. 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.
3. 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.
4. 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.
Output

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


Matplotlib.
Scatter Plot using Matplotlib
Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
Python Code

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

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:
1. Sample Data:
• The script uses hypothetical data for BRICS nations, including population and per
capita income.
2. Scaling for Visualization:
• Circle sizes are scaled down from population values to enhance visualization.
3. Color Assignment:
• Different colors are assigned based on the index of each country.
4. Scatter Plot:
• The scatter function is used to create a scatter plot with varying circle sizes and
colors.
5. Annotations:
• Each point on the plot is annotated with the country name for clarity.
6. Colorbar:
• A colorbar is added to the plot, providing a reference for the color index.
7. Labels and Title:
• Labels for the x-axis, y-axis, and a title are included to provide context.
8. 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.
Q-5)
a) Write a Python program to Demonstrate how to Draw a Histogram Plot using
Matplotlib.

Histogram Plot using Matplotlib


Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.
Python Code

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

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:
1. Random Data Generation:
• The script generates example data representing student scores using a normal
distribution (np.random.normal).
2. 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.
3. 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.
4. 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.
Output

b) Write a Python program to Demonstrate how to Draw a Pie Chart using


Matplotlib.

Pie Chart using Matplotlib


Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
Python Code
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()
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.
1. 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.
2. 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.
3. Title:
• The script adds a title to the pie chart, enhancing the overall context.
4. 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.
Output
Q-6) a) Write a Python program to illustrate Linear Plotting using Matplotlib.

Linear Plotting using Matplotlib


Write a Python program to illustrate Linear Plotting using Matplotlib.
Python Code

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

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:
1. Hypothetical Data:
• The script uses hypothetical data representing the number of runs scored in each
over of a T20 cricket match.
2. 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.
3. 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.
4. Grid:
• The plot includes a grid for better readability.
5. 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.
Output

b) Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.

Linear Plotting with line formatting using Matplotlib


Write a Python program to illustrate liner plotting with line formatting using Matplotlib.
Python Code

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()
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:
1. 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.
2. 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.
3. Grid:
• The plot includes a grid for better readability.
4. 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.
Output
Q-7) Write a Python program which explains uses of customizing seaborn plots with
Aesthetic functions.

Seaborn plots with Aesthetic functions


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

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

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:
1. Data Generation:
• The script uses numpy to generate a series of sine wave plots.
2. 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).
3. Customized Aesthetics:
• The sinplot function generates multiple sine wave plots with varying frequencies and
amplitudes.
4. 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.
Output
Q-8) Write a Python program to draw 3D Plots using Plotly Libraries.

Bokeh line graph using Annotations and Legends


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.
Python Code

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

The provided Python script demonstrates the use of the Bokeh library to create interactive data
visualizations with multiple plots. Here’s a concise overview:
1. Data Generation:
• The script generates example data (x and y) using NumPy to represent sine waves.
2. Interactive Tools:
• Bokeh’s interactive tools (TOOLS) are enabled for features like pan, zoom, reset,
and save.
3. Multiple Plots:
• Two separate plots (p1 and p2) are created with different visualizations, including
circles, lines, and markers.
4. Legend and Titles:
• Legends are added to distinguish between different elements in the plots.
• Titles are provided for each plot.
5. Grid Layout:
• The gridplot function is used to arrange the plots in a grid layout.
6. 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.
Output
Q-9) Write a Python program to draw Time Series using Plotly Libraries.

3D Plots using Plotly Libraries


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

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

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.
Output
Q-10) Write a Python program to draw Time Series using Plotly Libraries.

Time Series using Plotly Libraries


Write a Python program to draw Time Series using Plotly Libraries.
Python Code -Example 1
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()

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:
1. 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.
2. Plotly Express:
• Plotly Express (px) is employed to create an interactive line plot with the exchange
rate data.
3. 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’).
4. Title:
• The plot is given a title, ‘Dollar vs Rupee,’ for context.
5. 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.
Output
Python Code -Example 2
import pandas as pd
import plotly.express as px

runs_scored = pd.read_csv('AusVsInd.csv')
fig = px.line(runs_scored, x='Overs', y=['AUS', 'IND'], markers=True)
fig.update_layout(title='Australia vs India ODI Match', xaxis_title='OVERS', yaxis_title='RUNS',
legend_title='Country')

fig.show()

The provided Python script utilizes the Plotly Express library to create an interactive line plot
comparing the runs scored by Australia (AUS) and India (IND) over a series of overs in an ODI
cricket match. Here’s a concise overview:
1. Data Import:
• The script uses Pandas to read runs scored data from a CSV file (‘AusVsInd.csv’).
2. Plotly Express:
• Plotly Express (px) is employed to create an interactive line plot.
• The x-axis represents overs (‘Overs’), and the y-axis represents runs scored by
Australia and India.
3. Markers:
• Markers are added to the plot for each data point to enhance visibility.
4. Customized Layout:
• The layout is customized with a title (‘Australia vs India ODI Match’), x-axis label
(‘OVERS’), y-axis label (‘RUNS’), and legend title (‘Country’).
5. Interactive Display:
• The show method is called on the figure (fig) to display the interactive plot.
This script serves as an excellent example for readers interested in using Plotly Express for
comparing and visualizing data, particularly in the context of sports analytics or cricket match
statistics. The interactive features make it easy for users to explore the data interactively.
Output
Bar Graph for runs scored every over

#Bar Graph of Runs scored every Over


import pandas as pd
import plotly.express as px

runs_scored = pd.read_csv('AusVsInd.csv')

fig = px.bar(runs_scored, x='Overs', y=['AUS_RPO', 'IND_RPO'], barmode='group')


fig.update_layout(title='Australia vs India ODI Match', xaxis_title='OVERS', yaxis_title='RUNS',
legend_title='Country')

fig.show()

The provided Python script uses the Plotly Express library to create an interactive grouped bar
graph comparing the runs per over (RPO) scored by Australia (AUS) and India (IND) in an ODI
cricket match. Here’s a concise overview:
1. Data Import:
• The script uses Pandas to read runs scored data from a CSV file (‘AusVsInd.csv’).
2. Plotly Express:
• Plotly Express (px) is employed to create an interactive grouped bar graph.
• The x-axis represents overs (‘Overs’), and the y-axis represents runs per over scored
by Australia and India.
3. Grouped Bars:
• Bars are grouped for each over, and the bar mode is set to ‘group’ to display bars
side by side.
4. Customized Layout:
• The layout is customized with a title (‘Australia vs India ODI Match’), x-axis label
(‘OVERS’), y-axis label (‘RUNS’), and legend title (‘Country’).
5. Interactive Display:
• The show method is called on the figure (fig) to display the interactive grouped bar
graph.
This script serves as an illustrative example for readers interested in using Plotly Express to
visualize and compare runs scored per over by different teams in a cricket match. The interactive
nature of the graph allows users to explore the data interactively.
Output

You might also like