Python 3 Labo
Python 3 Labo
Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
Python Code
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
Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
Python Code
# Add colorbar
plt.colorbar(scatter, label='Index')
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.
Output
Question: Histogram Plot using Matplotlib
Write a Python program to Demonstrate how to Draw a Histogram Plot using
Matplotlib.
Python Code
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:
Output
Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
Python Code
# Add title
plt.title('FIFA World Cup Wins by Country')
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
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')
# Display the plot
plt.axis('equal') # Equal aspect ratio ensures that the pie chart is
circular.
plt.show()
The provided Python script, an extension of the previous pie chart example, enhances
the pie chart’s autopct (automatic percentage display) to display actual win counts for
each country. Here’s a concise overview:
The script defines a custom make_autopct function that takes the values (win counts) as
input.
Inside this function, a nested function my_autopct calculates the actual win count based
on the percentage.
1. Enhanced Autopct in Pie Chart:
The autopct parameter in the pie function is set to the custom autopct function,
resulting in the display of actual win counts.
2. Display:
The script creates and displays the pie chart with enhanced autopct for a more
informative representation of the data.
This script is a valuable addition for readers seeking to customize autopct in pie charts,
providing a more detailed insight into the data being visualized.
Output
Question: Linear Plotting using Matplotlib
Write a Python program to illustrate Linear Plotting using Matplotlib.
Python Code
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.
Output
Question: Linear Plotting with line formatting using Matplotlib
Write a Python program to illustrate liner plotting with line formatting using Matplotlib.
Python Code
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:
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: 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()
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
Question: 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 30 02:17:24 2023
@author: putta
"""
import numpy as np
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
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.circle(x, y, legend_label="sin(x)")
p2.line(x, y, legend_label="sin(x)")
p2.legend.title = 'Lines'
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
Question: 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
# 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.
1. Import Libraries:
We start by importing the necessary libraries, including plotly.express for interactive
visualizations.
2. Data Loading:
We load the Gapminder dataset and filter it to include only Asian countries.
3. 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.
4. 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 2 15:23:19 2023
@author: putta
"""
import pandas as pd
import plotly.express as px
dollar_conv = pd.read_csv('CUR_DLR_INR.csv')
CUR_DLR_INR.csv
CUR_DLR_INRDownload
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()
AusVsInd.csv File
AusVsInd.csvDownload
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
runs_scored = pd.read_csv('AusVsInd.csv')
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
Question: Maps using Plotly Libraries
import plotly.express as px
import pandas as pd
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.
1. Import Libraries:
We start by importing the necessary libraries, including plotly.express for easy and
interactive visualizations.
2. 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.
3. Choropleth Map:
The choropleth map is created using px.choropleth.
Key parameters include:
locations: ISO codes of countries.
color: GDP per Capita, determining the color intensity on the map.
4. 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
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()
CSV File
JSON File
You can obtain the JSON file used in this program by clicking on the button below.
1. 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.
2. 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.
3. 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.
4. Choropleth Map:
The choropleth map is generated using px.choropleth. Key parameters include:
locations: State IDs for mapping.
hover_data: Additional information displayed on hover, including density, sex ratio, and
population.
title: Title of the map.
5. 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
https://moodle.sit.ac.in/blog/data-visualization-with-python-bcs358d/#03a