DataVisulization_with_Python.123
DataVisulization_with_Python.123
1a. Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
Python Code:
Python Code :
Output
Enter a value: 987654
Not Palindrome
4 appears 1 times
5 appears 1 times
6 appears 1 times
7 appears 1 times
8 appears 1 times
9 appears 1 times
Enter a value: 123321
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 2 times
Question 2
Fibonacci Sequence
2a. 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.
Python 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: 6
fn(6) = 5
Enter a number: -3
Input should be greater than 0
Enter a number: abc
Try with numeric value
Output :
Enter a binary number: 101010
42
Enter an octal number: 755
1ED
Enter a binary number: 11011a
Invalid literal in input with base 2
Enter an octal number: 1298
Invalid literal in input with base 8
Question 3
Sentence Statistics
3a. Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters and lowercase letters.
Python 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 : 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
Enter a sentence: Python is Fun!
This sentence has 3 words
This sentence has 0 digits
3 uppercase letters
9 lowercase letters
Enter a sentence: Hello, World! 123
This sentence has 3 words
This sentence has 3 digits
1 uppercase letters
12 lowercase letters
String Similarity :
3b. Write a Python program to find the string similarity between two given strings.
Python Code :
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)
----------------------------------------EOP----------------------------------------------------
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.
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.
Output :
Enter String 1 : Python Exercises
Enter String 2 : Python Exercise
Similarity between strings "Python Exercises" and "Python Exercise" is :
0.967741935483871
Enter String 1 : Python Exercises
Enter String 2 : Python Exercises
Similarity between strings "Python Exercises" and "Python Exercises" is : 1.0
Question 4 :
Bar Plot using Matplotlib :
4a. Write a Python program to Demonstrate how to Draw a Bar Plot using
Matplotlib.
Python Code :
Python Code
# Add title
plt.title('FIFA World Cup Wins by Country')
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return '{v:d}'.format(v=val)
return my_autopct
# Add title
plt.title('FIFA World Cup Wins by Country')
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.
Output:
Question 7
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:
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.
Output:
Question 8
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:
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.
Output:
Question 9
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:
Another Example :
import plotly.express as px
df = px.data.gapminder().query("continent=='Asia'")
fig = px.line_3d(df, x="gdpPercap", y="pop", z="year", color='country', title='Economic
Evolution of Asian Countries Over Time')
fig.show()
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:
Question 10
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()
CUR_DLR_INR.csv
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.
Output :
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()
AusVsInd.csv File
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:
Data Import:
The script uses Pandas to read runs scored data from a CSV file (‘AusVsInd.csv’).
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.
Markers:
Markers are added to the plot for each data point to enhance visibility.
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’).
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:
Example 3:
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:
Data Import:
The script uses Pandas to read runs scored data from a CSV file (‘AusVsInd.csv’).
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.
Grouped Bars:
Bars are grouped for each over, and the bar mode is set to ‘group’ to display bars side by
side.
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’).
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:
Maps using Plotly Libraries
10b. Write a Python program for creating Maps using Plotly Libraries.
Python Code -Example 1
import plotly.express as px
import pandas as pd
# Import data from GitHub
data=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_w
ith_codes.csv')
# Create basic choropleth map
fig = px.choropleth(data, locations='iso_alpha', color='gdpPercap', hover_name='country',
projection='natural earth', title='GDP per Capita by Country')
fig.show()
In this Python program, we utilize Plotly Express to create an interactive choropleth map
visualizing GDP per Capita by country. The dataset used is sourced from Gapminder,
providing a comprehensive view of economic indicators globally.
Import Libraries:
We start by importing the necessary libraries, including plotly.express for easy and
interactive visualizations.
Data Loading:
The program fetches data from a CSV file hosted on GitHub using pd.read_csv. The
dataset includes information about countries, their ISO codes, and GDP per Capita.
Choropleth Map:
The choropleth map is created using px.choropleth.
Interactive Exploration:
The resulting choropleth map is interactive, enabling users to hover over countries to see
GDP per Capita values.
Users can explore and compare GDP per Capita across different countries. Darker colors
indicate higher GDP per Capita. This program demonstrates the simplicity and power of
Plotly Express for creating data-driven visualizations. The choropleth map offers an
intuitive way to understand global economic
disparities. Feel free to customize the description based on additional details you’d like to
highlight or any specific insights you’ve gained from the visualization.
Output :
Python Code -Example 2
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()
Program Overview:
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.
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.
Output: