Assignment 2
Basic Data Visualization Tools
Lab Assignment
SET A
1. Generate a dataset representing the daily temperatures (in °C) recorded over 50 days. Visualize the dataset using a Line Chart and Scatter Plot. Apply appropriate colors, titles, axis labels, and styling
options. [Attributes for dataset – (Date, Temperature (°C))]
2. Consider the following dataset representing the number of books available in different sections of a library:
sections = ["Science", "Literature", "History", "Technology", "Commerce"]
books = [450, 380, 250, 520, 310]
Create a Bar Chart to visualize the number of books available in each section. Use different bar colors, add an appropriate title, and label both axes.
3. Generate a suitable dataset containing the ages of 100 gym members. Create a Histogram to visualize the age distribution of the members. Customize the graph using appropriate bins, colors,
title, and labels. [Attributes for dataset – Member ID, Age]
4. A company conducted a survey to determine the preferred mode of transportation among employees as shown below:
transport = ["Bus", "Train", "Car", "Bike", "Bicycle"], employees = [120, 80, 60, 90, 30]
Create a Pie Chart to represent the percentage of employees using each mode of transportation. Display the percentage contribution of each category.
SET B
1. The environmental department collected the following information for six cities:
cities = ["A", "B", "C", "D", "E", "F"],
population = [5, 8, 12, 15, 20, 25]
pollution = [40, 48, 55, 63, 72, 85],
green_cover = [350, 300, 250, 220, 180, 150]
Create a Bar Chart showing pollution levels and a Bubble Plot showing the relationship among population, pollution, and green cover.
import pandas as pd
import matplotlib.pyplot as plt
# -----------------------------------------
# Given Data
# -----------------------------------------
cities = ["A", "B", "C", "D", "E", "F"]
population = [5, 8, 12, 15, 20, 25]
pollution = [40, 48, 55, 63, 72, 85]
green_cover = [350, 300, 250, 220, 180, 150]
# -----------------------------------------
# Create DataFrame
# -----------------------------------------
data = {
"City": cities,
"Population": population,
"Pollution": pollution,
"Green Cover": green_cover
}
df = pd.DataFrame(data)
print("Environmental Data:")
print(df)
# =========================================
# 1. BAR CHART - POLLUTION LEVELS
# =========================================
plt.figure(figsize=(8, 5))
plt.bar(
df["City"],
df["Pollution"],
edgecolor="black"
)
plt.xlabel("City")
plt.ylabel("Pollution Level")
plt.title("Pollution Levels in Different Cities")
plt.grid(axis="y", linestyle="--", alpha=0.5)
plt.tight_layout()
plt.show()
# =========================================
# 2. BUBBLE PLOT
# =========================================
plt.figure(figsize=(9, 6))
plt.scatter(
df["Population"],
df["Pollution"],
s=df["Green Cover"],
alpha=0.6
)
# Add city labels
for i in range(len(df)):
plt.text(
df["Population"][i],
df["Pollution"][i],
df["City"][i]
)
plt.xlabel("Population (Million)")
plt.ylabel("Pollution Level")
plt.title("Bubble Plot: Population, Pollution and Green Cover")
plt.grid(True, linestyle="--", alpha=0.5)
plt.tight_layout()
plt.show()
2. Load the Titanic dataset (titanic.csv)
Create a histogram showing the number of passengers in each passenger class. Create a Pie Chart showing the survival distribution.
import pandas as pd
import matplotlib.pyplot as plt
# Load Titanic dataset
df = pd.read_csv("titanic.csv")
# Display first five records
print(df.head())
# -------------------------------
# 1. Histogram: Passengers in each class
# -------------------------------
plt.figure(figsize=(7, 5))
plt.hist(df["Pclass"], bins=[0.5, 1.5, 2.5, 3.5],
edgecolor="black", rwidth=0.8)
plt.xticks([1, 2, 3])
plt.xlabel("Passenger Class")
plt.ylabel("Number of Passengers")
plt.title("Number of Passengers in Each Passenger Class")
plt.show()
# -------------------------------
# 2. Pie Chart: Survival Distribution
# -------------------------------
survival_counts = df["Survived"].value_counts()
labels = ["Not Survived", "Survived"]
plt.figure(figsize=(6, 6))
plt.pie(
survival_counts,
labels=labels,
autopct="%1.1f%%",
startangle=90
)
plt.title("Titanic Survival Distribution")
plt.show()
3. Write a Python program to draw scatter plots to compare two features of the iris dataset.
import pandas as pd
import matplotlib.pyplot as plt
# Load Iris dataset
df = pd.read_csv("iris.csv")
# Display first five records
print(df.head())
# Create scatter plot
plt.figure(figsize=(8, 5))
plt.scatter(df["sepal_length"], df["petal_length"])
# Add labels and title
plt.xlabel("Sepal Length")
plt.ylabel("Petal Length")
plt.title("Scatter Plot: Sepal Length vs Petal Length")
# Display grid
plt.grid(True)
# Show plot
plt.show()
SET C
1. Banking Loan Analysis
Generate a dataset containing loan information.
Attributes: Customer Age, Loan Amount, Annual Income, Credit Score
Perform the following tasks:
a) Create Histograms for Loan Amount and Credit Score.
b) Generate Scatter Plots for Income vs Loan Amount.
c) Create Bubble Plots using Income, Credit Score, and Loan Amount.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# -----------------------------------------
# Generate Banking Loan Dataset
# -----------------------------------------
np.random.seed(42)
data = {
"Customer Age": np.random.randint(21, 61, 50),
"Loan Amount": np.random.randint(50000, 1000000, 50),
"Annual Income": np.random.randint(200000, 2000000, 50),
"Credit Score": np.random.randint(500, 850, 50)
}
df = pd.DataFrame(data)
# Display dataset
print("Banking Loan Dataset:")
print(df)
# Save dataset as CSV file
df.to_csv("banking_loan.csv", index=False)
# -----------------------------------------
# a) Histograms for Loan Amount
# and Credit Score
# -----------------------------------------
# Histogram for Loan Amount
plt.figure(figsize=(8, 5))
plt.hist(df["Loan Amount"], bins=10, edgecolor="black")
plt.xlabel("Loan Amount")
plt.ylabel("Number of Customers")
plt.title("Distribution of Loan Amount")
plt.show()
# Histogram for Credit Score
plt.figure(figsize=(8, 5))
plt.hist(df["Credit Score"], bins=10, edgecolor="black")
plt.xlabel("Credit Score")
plt.ylabel("Number of Customers")
plt.title("Distribution of Credit Score")
plt.show()
# -----------------------------------------
# b) Scatter Plot: Income vs Loan Amount
# -----------------------------------------
plt.figure(figsize=(8, 5))
plt.scatter(df["Annual Income"], df["Loan Amount"])
plt.xlabel("Annual Income")
plt.ylabel("Loan Amount")
plt.title("Annual Income vs Loan Amount")
plt.grid(True)
plt.show()
# -----------------------------------------
# c) Bubble Plot using Income,
# Credit Score and Loan Amount
# -----------------------------------------
plt.figure(figsize=(9, 6))
plt.scatter(
df["Annual Income"],
df["Credit Score"],
s=df["Loan Amount"] / 1000,
alpha=0.6
)
plt.xlabel("Annual Income")
plt.ylabel("Credit Score")
plt.title("Bubble Plot: Income, Credit Score and Loan Amount")
plt.grid(True)
plt.show()
2. Smart City Traffic Analysis
Generate a dataset showing monthly traffic statistics.
Attributes: Month, Cars, Two-Wheelers, Public Transport Users
Perform the following tasks:
a) Create Line Charts showing traffic trends.
b) Generate Area Plots for cumulative traffic volume.
c) Create Pie Charts showing transportation mode share.
d) Analyze urban mobility patterns and congestion trends
import pandas as pd
import matplotlib.pyplot as plt
# -----------------------------------------
# Generate Smart City Traffic Dataset
# -----------------------------------------
data = {
"Month": [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
],
"Cars": [
45000, 47000, 48000, 50000,
52000, 54000, 55000, 57000,
59000, 61000, 63000, 65000
],
"Two-Wheelers": [
60000, 62000, 64000, 66000,
68000, 70000, 72000, 74000,
76000, 78000, 80000, 82000
],
"Public Transport Users": [
30000, 31000, 32000, 33000,
35000, 36000, 37000, 38000,
40000, 41000, 43000, 45000
]
}
df = pd.DataFrame(data)
# Display dataset
print("Smart City Traffic Dataset:")
print(df)
# Save dataset
df.to_csv("smart_city_traffic.csv", index=False)
# -----------------------------------------
# a) Line Chart - Traffic Trends
# -----------------------------------------
plt.figure(figsize=(10, 6))
plt.plot(df["Month"], df["Cars"], marker="o", label="Cars")
plt.plot(df["Month"], df["Two-Wheelers"], marker="o",
label="Two-Wheelers")
plt.plot(df["Month"], df["Public Transport Users"],
marker="o", label="Public Transport Users")
plt.xlabel("Month")
plt.ylabel("Number of Users/Vehicles")
plt.title("Monthly Traffic Trends")
plt.xticks(rotation=45)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# -----------------------------------------
# b) Area Plot - Cumulative Traffic Volume
# -----------------------------------------
plt.figure(figsize=(10, 6))
plt.stackplot(
df["Month"],
df["Cars"],
df["Two-Wheelers"],
df["Public Transport Users"],
labels=[
"Cars",
"Two-Wheelers",
"Public Transport Users"
],
alpha=0.7
)
plt.xlabel("Month")
plt.ylabel("Traffic Volume")
plt.title("Cumulative Traffic Volume")
plt.xticks(rotation=45)
plt.legend(loc="upper left")
plt.tight_layout()
plt.show()
# -----------------------------------------
# c) Pie Chart - Transportation Mode Share
# -----------------------------------------
# Calculate total values for each transportation mode
cars_total = df["Cars"].sum()
two_wheeler_total = df["Two-Wheelers"].sum()
public_transport_total = df["Public Transport Users"].sum()
values = [
cars_total,
two_wheeler_total,
public_transport_total
]
labels = [
"Cars",
"Two-Wheelers",
"Public Transport"
]
plt.figure(figsize=(7, 7))
plt.pie(
values,
labels=labels,
autopct="%1.1f%%",
startangle=90
)
plt.title("Transportation Mode Share")
plt.show()
# -----------------------------------------
# d) Analyze Urban Mobility Patterns
# -----------------------------------------
df["Total Traffic"] = (
df["Cars"]
+ df["Two-Wheelers"]
+ df["Public Transport Users"]
)
print("\nMonthly Total Traffic:")
print(df[["Month", "Total Traffic"]])
# Find month with maximum traffic
max_month = df.loc[df["Total Traffic"].idxmax(), "Month"]
max_traffic = df["Total Traffic"].max()
# Find month with minimum traffic
min_month = df.loc[df["Total Traffic"].idxmin(), "Month"]
min_traffic = df["Total Traffic"].min()
print("\nUrban Mobility Analysis:")
print("Month with maximum traffic:", max_month)
print("Maximum traffic volume:", max_traffic)
print("Month with minimum traffic:", min_month)
print("Minimum traffic volume:", min_traffic)
# Calculate percentage increase in total traffic
first_month = df["Total Traffic"].iloc[0]
last_month = df["Total Traffic"].iloc[-1]
increase = ((last_month - first_month) / first_month) * 100
print("Overall traffic increase: {:.2f}%".format(increase))
No comments:
Post a Comment