Saturday, August 29, 2026

TYBCS DS & DA Assignment 3

 Assignment 3
Advanced Data Visualization tools

 Lab Assignment
SET A
1. A retail store has recorded the daily sales (₹) for two months. Create a suitable dataset and generate a Box Plot to identify any outliers. Customize the graph with appropriate title and labels.

import pandas as pd
import matplotlib.pyplot as plt

# -----------------------------------------
# Create Daily Sales Dataset for Two Months
# -----------------------------------------

data = {
    "Day": list(range(1, 61)),
    "Sales": [
        12500, 13200, 11800, 14500, 13900, 15200, 12800, 13500, 14200, 15000,
        15500, 14700, 13800, 12900, 14100, 13600, 14800, 15300, 13200, 12700,
        14500, 15100, 13900, 14300, 15700, 14900, 13500, 12800, 14000, 14600,
        15200, 13700, 14400, 15800, 14900, 13600, 14200, 15100, 14700, 13900,
        15500, 16000, 14800, 13400, 14100, 15300, 15900, 14600, 13800, 15000,
        16200, 14500, 13900, 14700, 15400, 16800, 14200, 13600, 15100, 17500,

        # Unusually high sales values (potential outliers)
        45000, 52000
    ]
}

df = pd.DataFrame(data)

# Display dataset
print("Daily Sales Dataset:")
print(df)

# Save dataset as CSV
df.to_csv("retail_sales.csv", index=False)


# -----------------------------------------
# Create Box Plot
# -----------------------------------------

plt.figure(figsize=(8, 6))

plt.boxplot(
    df["Sales"],
    patch_artist=True,
    showmeans=True
)

plt.title("Box Plot of Daily Retail Store Sales")
plt.ylabel("Daily Sales (₹)")
plt.xlabel("Retail Store")

plt.grid(axis="y", linestyle="--", alpha=0.7)

plt.show()


# -----------------------------------------
# Identify Outliers using IQR Method
# -----------------------------------------

Q1 = df["Sales"].quantile(0.25)
Q3 = df["Sales"].quantile(0.75)

IQR = Q3 - Q1

lower_limit = Q1 - 1.5 * IQR
upper_limit = Q3 + 1.5 * IQR

outliers = df[
    (df["Sales"] < lower_limit) |
    (df["Sales"] > upper_limit)
]

print("\nQ1:", Q1)
print("Q3:", Q3)
print("IQR:", IQR)

print("\nLower Limit:", lower_limit)
print("Upper Limit:", upper_limit)

print("\nOutliers:")
print(outliers)


2. Write a Python program to generate a box plot to show the Interquartile range and outliers for the three species for each feature using IRIS data set.

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

# Features of Iris dataset
features = [
    "sepal_length",
    "sepal_width",
    "petal_length",
    "petal_width"
]

# Species
species = ["setosa", "versicolor", "virginica"]

# -----------------------------------------
# Create Box Plots for Each Feature
# -----------------------------------------

fig, axes = plt.subplots(2, 2, figsize=(12, 8))

for ax, feature in zip(axes.ravel(), features):

    data = [
        df[df["species"] == s][feature]
        for s in species
    ]

    ax.boxplot(
        data,
        labels=species,
        patch_artist=True
    )

    ax.set_title("Box Plot of " + feature)
    ax.set_xlabel("Species")
    ax.set_ylabel(feature)
    ax.grid(axis="y", linestyle="--", alpha=0.5)

plt.suptitle(
    "Iris Dataset: IQR and Outliers for Each Feature",
    fontsize=14
)

plt.tight_layout()
plt.show()


# -----------------------------------------
# Calculate IQR and Outliers
# -----------------------------------------

print("\nIQR and Outlier Analysis")
print("=" * 50)

for feature in features:

    print("\nFeature:", feature)

    for s in species:

        values = df[df["species"] == s][feature]

        Q1 = values.quantile(0.25)
        Q3 = values.quantile(0.75)

        IQR = Q3 - Q1

        lower_limit = Q1 - 1.5 * IQR
        upper_limit = Q3 + 1.5 * IQR

        outliers = values[
            (values < lower_limit) |
            (values > upper_limit)
        ]

        print("\nSpecies:", s)
        print("Q1:", Q1)
        print("Q3:", Q3)
        print("IQR:", IQR)
        print("Lower Limit:", lower_limit)
        print("Upper Limit:", upper_limit)
        print("Number of Outliers:", len(outliers)) 


3. Create a dataset containing monthly values of Temperature, Humidity, Rainfall, and Wind Speed.Generate a Heat Map to visualize the correlation between these weather parameters. 

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# -----------------------------------------
# Create Monthly Weather Dataset
# -----------------------------------------

data = {
    "Month": [
        "January", "February", "March", "April",
        "May", "June", "July", "August",
        "September", "October", "November", "December"
    ],

    "Temperature": [
        18, 21, 25, 30, 34, 29,
        27, 28, 27, 25, 21, 18
    ],

    "Humidity": [
        55, 52, 48, 45, 42, 65,
        75, 78, 72, 65, 58, 54
    ],

    "Rainfall": [
        5, 8, 12, 20, 35, 180,
        250, 220, 190, 80, 25, 10
    ],

    "Wind Speed": [
        8, 9, 10, 12, 14, 18,
        20, 19, 17, 13, 10, 8
    ]
}

df = pd.DataFrame(data)

# Display dataset
print("Monthly Weather Dataset:")
print(df)

# Save dataset as CSV
df.to_csv("monthly_weather.csv", index=False)


# -----------------------------------------
# Calculate Correlation Matrix
# -----------------------------------------

correlation = df[
    ["Temperature", "Humidity", "Rainfall", "Wind Speed"]
].corr()

print("\nCorrelation Matrix:")
print(correlation)


# -----------------------------------------
# Generate Heat Map
# -----------------------------------------

plt.figure(figsize=(8, 6))

sns.heatmap(
    correlation,
    annot=True,
    cmap="coolwarm",
    fmt=".2f",
    linewidths=0.5
)

plt.title("Correlation Heat Map of Weather Parameters")
plt.xlabel("Weather Parameters")
plt.ylabel("Weather Parameters")

plt.tight_layout()
plt.show()


4. Create a dataset containing information about different products such as Price, Rating, and Number of Sales. Generate a Dendrogram to group similar products based on their characteristics. 

import pandas as pd
import matplotlib.pyplot as plt

from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.preprocessing import StandardScaler

# -----------------------------------------
# Create Product Dataset
# -----------------------------------------

data = {
    "Product": [
        "Laptop", "Mobile", "Tablet", "Headphones",
        "Smartwatch", "Camera", "Television",
        "Speaker", "Keyboard", "Monitor"
    ],

    "Price": [
        60000, 25000, 35000, 5000, 8000,
        45000, 55000, 7000, 3000, 15000
    ],

    "Rating": [
        4.5, 4.2, 4.4, 4.0, 4.1,
        4.3, 4.6, 4.0, 4.2, 4.4
    ],

    "Number of Sales": [
        1200, 3500, 2200, 5000, 4200,
        1500, 1000, 3800, 5500, 2000
    ]
}

df = pd.DataFrame(data)

# Display dataset
print("Product Dataset:")
print(df)

# Save dataset as CSV
df.to_csv("product_data.csv", index=False)


# -----------------------------------------
# Select Numerical Features
# -----------------------------------------

features = [
    "Price",
    "Rating",
    "Number of Sales"
]

X = df[features]


# -----------------------------------------
# Standardize the Data
# -----------------------------------------

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)


# -----------------------------------------
# Perform Hierarchical Clustering
# -----------------------------------------

linked = linkage(
    X_scaled,
    method="ward"
)


# -----------------------------------------
# Generate Dendrogram
# -----------------------------------------

plt.figure(figsize=(12, 7))

dendrogram(
    linked,
    labels=df["Product"].values,
    orientation="top",
    distance_sort="ascending"
)

plt.title("Dendrogram of Similar Products")
plt.xlabel("Products")
plt.ylabel("Euclidean Distance")

plt.xticks(rotation=45)

plt.tight_layout()
plt.show()
 

5. A survey was conducted to identify customers who use Netflix and Amazon Prime. Create a Venn Diagram showing - Customers using only Netflix, Customers using only Amazon Prime,Customers using both services
import pandas as pd  

 import matplotlib.pyplot as plt
from matplotlib_venn import venn2

# -----------------------------------------
# Create Customer Survey Dataset
# -----------------------------------------

data = {
    "Customer": [
        "C1", "C2", "C3", "C4", "C5",
        "C6", "C7", "C8", "C9", "C10",
        "C11", "C12"
    ],

    "Netflix": [
        "Yes", "Yes", "Yes", "Yes", "No",
        "No", "Yes", "No", "Yes", "No",
        "Yes", "No"
    ],

    "Amazon Prime": [
        "No", "Yes", "No", "Yes", "Yes",
        "Yes", "No", "Yes", "Yes", "No",
        "No", "Yes"
    ]
}

df = pd.DataFrame(data)

# Display dataset
print("Customer Survey Dataset:")
print(df)


# -----------------------------------------
# Create Sets
# -----------------------------------------

netflix_customers = set(
    df[df["Netflix"] == "Yes"]["Customer"]
)

amazon_customers = set(
    df[df["Amazon Prime"] == "Yes"]["Customer"]
)


# -----------------------------------------
# Display Customer Groups
# -----------------------------------------

only_netflix = netflix_customers - amazon_customers
only_amazon = amazon_customers - netflix_customers
both_services = netflix_customers & amazon_customers

print("\nCustomers using only Netflix:")
print(only_netflix)

print("\nCustomers using only Amazon Prime:")
print(only_amazon)

print("\nCustomers using both services:")
print(both_services)


# -----------------------------------------
# Generate Venn Diagram
# -----------------------------------------

plt.figure(figsize=(8, 6))

venn = venn2(
    [netflix_customers, amazon_customers],
    set_labels=("Netflix", "Amazon Prime")
)

plt.title("Netflix and Amazon Prime Customer Survey")

plt.show()

 

Set B
1. Download the Auto MPG Dataset (mpg.csv)[ MPG, Horsepower, Weight, Cylinders, Acceleration.] and perform the following tasks:
a. Create Box Plots for MPG and Horsepower, Identify outliers
b. Generate a Heat Map showing correlations among numerical attributes.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# -----------------------------------------
# Load Auto MPG Dataset
# -----------------------------------------

df = pd.read_csv("mpg.csv")

print("First five records:")
print(df.head())

print("\nDataset Information:")
print(df.info())


# -----------------------------------------
# Select Required Numerical Attributes
# -----------------------------------------

columns = [
    "MPG",
    "Horsepower",
    "Weight",
    "Cylinders",
    "Acceleration"
]

data = df[columns].copy()

# Convert columns to numeric
# Invalid values will be converted to NaN
for column in columns:
    data[column] = pd.to_numeric(data[column], errors="coerce")

# Remove missing values
data = data.dropna()


# =========================================
# a) BOX PLOTS
# =========================================

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.boxplot(data["MPG"])
plt.title("Box Plot of MPG")
plt.ylabel("MPG")

plt.subplot(1, 2, 2)
plt.boxplot(data["Horsepower"])
plt.title("Box Plot of Horsepower")
plt.ylabel("Horsepower")

plt.tight_layout()
plt.show()


# -----------------------------------------
# Identify Outliers using IQR
# -----------------------------------------

def find_outliers(column):
    Q1 = data[column].quantile(0.25)
    Q3 = data[column].quantile(0.75)

    IQR = Q3 - Q1

    lower_limit = Q1 - 1.5 * IQR
    upper_limit = Q3 + 1.5 * IQR

    outliers = data[
        (data[column] < lower_limit) |
        (data[column] > upper_limit)
    ]

    print("\n", column)
    print("Q1 =", Q1)
    print("Q3 =", Q3)
    print("IQR =", IQR)
    print("Lower Limit =", lower_limit)
    print("Upper Limit =", upper_limit)
    print("Number of Outliers =", len(outliers))

    print("Outlier Values:")
    print(outliers[column].values)


# Find MPG outliers
find_outliers("MPG")

# Find Horsepower outliers
find_outliers("Horsepower")


# =========================================
# b) CORRELATION HEAT MAP
# =========================================

correlation = data[columns].corr()

print("\nCorrelation Matrix:")
print(correlation)

plt.figure(figsize=(9, 7))

sns.heatmap(
    correlation,
    annot=True,
    cmap="coolwarm",
    fmt=".2f",
    linewidths=0.5
)

plt.title("Correlation Heat Map of Auto MPG Dataset")
plt.xlabel("Numerical Attributes")
plt.ylabel("Numerical Attributes")

plt.tight_layout()
plt.show()
 

2. Create a dataset containing movie titles available on Netflix, Amazon Prime, and Disney+ and perform the following tasks:
a. Create a Venn Diagram comparing Netflix and Amazon Prime movie collections.
b. Generate a Word Cloud using movie genres or titles.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib_venn import venn2
from wordcloud import WordCloud

# -----------------------------------------
# Create Movie Dataset
# -----------------------------------------

data = {
    "Movie": [
        "Inception",
        "Avengers",
        "The Lion King",
        "Titanic",
        "Interstellar",
        "Frozen",
        "Joker",
        "Black Panther",
        "Toy Story",
        "Spider Man",
        "The Dark Knight",
        "Moana",
        "Avatar",
        "Iron Man",
        "Coco"
    ],

    "Netflix": [
        "Yes", "No", "Yes", "Yes", "Yes",
        "No", "Yes", "No", "No", "Yes",
        "Yes", "No", "Yes", "No", "No"
    ],

    "Amazon Prime": [
        "Yes", "Yes", "No", "Yes", "No",
        "Yes", "No", "Yes", "Yes", "Yes",
        "No", "Yes", "No", "Yes", "No"
    ],

    "Disney+": [
        "No", "Yes", "Yes", "No", "No",
        "Yes", "No", "Yes", "Yes", "No",
        "No", "Yes", "Yes", "Yes", "Yes"
    ]
}

df = pd.DataFrame(data)

# Display dataset
print("Movie Dataset:")
print(df)

# Save dataset
df.to_csv("streaming_movies.csv", index=False)


# =========================================
# a) VENN DIAGRAM
# =========================================

# Create Netflix movie set
netflix_movies = set(
    df[df["Netflix"] == "Yes"]["Movie"]
)

# Create Amazon Prime movie set
amazon_movies = set(
    df[df["Amazon Prime"] == "Yes"]["Movie"]
)

# Display movie groups
print("\nNetflix Movies:")
print(netflix_movies)

print("\nAmazon Prime Movies:")
print(amazon_movies)

print("\nMovies Available on Both:")
print(netflix_movies & amazon_movies)

print("\nMovies Only on Netflix:")
print(netflix_movies - amazon_movies)

print("\nMovies Only on Amazon Prime:")
print(amazon_movies - netflix_movies)


# Create Venn Diagram
plt.figure(figsize=(8, 6))

venn2(
    [netflix_movies, amazon_movies],
    set_labels=("Netflix", "Amazon Prime")
)

plt.title("Netflix vs Amazon Prime Movie Collection")

plt.show()


# =========================================
# b) WORD CLOUD USING MOVIE TITLES
# =========================================

# Combine all movie titles
text = " ".join(df["Movie"])

# Generate Word Cloud
wordcloud = WordCloud(
    width=1000,
    height=600,
    background_color="white",
    max_words=100
).generate(text)

# Display Word Cloud
plt.figure(figsize=(12, 7))

plt.imshow(wordcloud, interpolation="bilinear")

plt.axis("off")

plt.title("Word Cloud of Movie Titles")

plt.show()
 

3. Create a dataset containing information about different cities.
Attributes: City, Population, GDP, Literacy Rate
Perform the following tasks:
a. Generate a Treemap showing city-wise population distribution.
b. Create a 3D Scatter Plot using Population, GDP, and Literacy Rate.

import pandas as pd
import matplotlib.pyplot as plt
import squarify
from mpl_toolkits.mplot3d import Axes3D

# -----------------------------------------
# Create City Dataset
# -----------------------------------------

data = {
    "City": [
        "Mumbai",
        "Delhi",
        "Bengaluru",
        "Chennai",
        "Hyderabad",
        "Pune",
        "Ahmedabad",
        "Kolkata",
        "Jaipur",
        "Nashik"
    ],

    "Population": [
        20.7, 19.0, 13.6, 11.5, 10.8,
        7.0, 8.0, 14.8, 4.0, 2.2
    ],

    "GDP": [
        310, 293, 110, 78, 75,
        69, 47, 150, 30, 25
    ],

    "Literacy Rate": [
        89.7, 86.2, 88.7, 90.2, 83.3,
        89.4, 88.3, 87.1, 84.0, 82.3
    ]
}

df = pd.DataFrame(data)

# Display dataset
print("City Dataset:")
print(df)

# Save dataset
df.to_csv("city_data.csv", index=False)


# =========================================
# a) TREEMAP
# =========================================

plt.figure(figsize=(12, 7))

squarify.plot(
    sizes=df["Population"],
    label=df["City"],
    alpha=0.8
)

plt.title("City-wise Population Distribution")
plt.axis("off")

plt.show()


# =========================================
# b) 3D SCATTER PLOT
# =========================================

fig = plt.figure(figsize=(10, 7))

ax = fig.add_subplot(111, projection="3d")

# Create 3D scatter plot
scatter = ax.scatter(
    df["Population"],
    df["GDP"],
    df["Literacy Rate"],
    s=80
)

# Add city names
for i in range(len(df)):
    ax.text(
        df["Population"][i],
        df["GDP"][i],
        df["Literacy Rate"][i],
        df["City"][i]
    )

# Labels
ax.set_xlabel("Population (Million)")
ax.set_ylabel("GDP (Billion)")
ax.set_zlabel("Literacy Rate (%)")

ax.set_title(
    "3D Scatter Plot: Population, GDP and Literacy Rate"
)

plt.show()
 

4. Download a publicly available Earthquake Dataset (CSV format) containing latitude, longitude, and magnitude information.
Perform the following tasks: 
a. Create a Geospatial Visualization showing earthquake locations on a map.
b. Use marker size or color to represent earthquake magnitude.

Required Libraries

Install the required libraries:

pip install pandas matplotlib seaborn geopandas

 

import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd

# -----------------------------------------
# Load Earthquake Dataset
# -----------------------------------------

df = pd.read_csv("earthquake.csv")

# Display first five records
print("Earthquake Dataset:")
print(df.head())

# Display column names
print("\nColumn Names:")
print(df.columns)


# -----------------------------------------
# Select Required Columns
# -----------------------------------------

earthquakes = df[
    ["latitude", "longitude", "magnitude"]
].dropna()

print("\nCleaned Earthquake Data:")
print(earthquakes.head())


# -----------------------------------------
# Create GeoDataFrame
# -----------------------------------------

geometry = gpd.points_from_xy(
    earthquakes["longitude"],
    earthquakes["latitude"]
)

gdf = gpd.GeoDataFrame(
    earthquakes,
    geometry=geometry,
    crs="EPSG:4326"
)


# -----------------------------------------
# Load World Map
# -----------------------------------------

world = gpd.read_file(
    gpd.datasets.get_path("naturalearth_lowres")
)


# -----------------------------------------
# Create Geospatial Visualization
# -----------------------------------------

fig, ax = plt.subplots(figsize=(14, 8))

# Plot world map
world.plot(
    ax=ax,
    edgecolor="black",
    facecolor="lightgray"
)

# Plot earthquake locations
gdf.plot(
    ax=ax,
    column="magnitude",
    cmap="Reds",
    markersize=gdf["magnitude"] ** 3,
    alpha=0.7,
    legend=True,
    legend_kwds={
        "label": "Earthquake Magnitude",
        "orientation": "vertical"
    }
)

plt.title("Global Earthquake Locations and Magnitudes")
plt.xlabel("Longitude")
plt.ylabel("Latitude")

plt.show()
 

SET C
1. Download climate data for multiple countries.
Attributes: Country, Average Temperature, CO₂ Emissions, Rainfall, Forest Area Perform the following tasks:
a. Generate a Heat Map showing feature correlations.
b. Create a 3D Scatter Plot using Temperature, CO₂ Emissions, and Forest Area.
c. Create a Geospatial Visualization displaying country-wise climate indicators.

Required Libraries

Install the required libraries:

pip install pandas matplotlib seaborn geopandas

 

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import geopandas as gpd

# -----------------------------------------
# Load Climate Dataset
# -----------------------------------------

df = pd.read_csv("climate_data.csv")

print("First five records:")
print(df.head())

print("\nColumn Names:")
print(df.columns)


# -----------------------------------------
# Select Numerical Features
# -----------------------------------------

features = [
    "Average Temperature",
    "CO2 Emissions",
    "Rainfall",
    "Forest Area"
]

# Convert numerical columns to numeric
for column in features:
    df[column] = pd.to_numeric(df[column], errors="coerce")

# Remove missing values
df_clean = df.dropna(subset=features)


# =========================================
# a) CORRELATION HEAT MAP
# =========================================

correlation = df_clean[features].corr()

print("\nCorrelation Matrix:")
print(correlation)

plt.figure(figsize=(9, 7))

sns.heatmap(
    correlation,
    annot=True,
    cmap="coolwarm",
    fmt=".2f",
    linewidths=0.5
)

plt.title("Correlation Heat Map of Climate Indicators")
plt.xlabel("Climate Parameters")
plt.ylabel("Climate Parameters")

plt.tight_layout()
plt.show()


# =========================================
# b) 3D SCATTER PLOT
# =========================================

fig = plt.figure(figsize=(10, 7))

ax = fig.add_subplot(111, projection="3d")

scatter = ax.scatter(
    df_clean["Average Temperature"],
    df_clean["CO2 Emissions"],
    df_clean["Forest Area"],
    s=70,
    c=df_clean["Rainfall"],
    cmap="viridis",
    alpha=0.8
)

# Axis labels
ax.set_xlabel("Average Temperature")
ax.set_ylabel("CO2 Emissions")
ax.set_zlabel("Forest Area")

ax.set_title(
    "3D Scatter Plot: Temperature, CO2 Emissions and Forest Area"
)

# Color bar represents rainfall
cbar = plt.colorbar(scatter, ax=ax, pad=0.1)
cbar.set_label("Rainfall")

plt.tight_layout()
plt.show()


# =========================================
# c) GEOSPATIAL VISUALIZATION
# =========================================

# Load world map
world = gpd.read_file(
    "https://naturalearth.s3.amazonaws.com/110m_cultural/"
    "ne_110m_admin_0_countries.zip"
)

# Match country names
# Adjust this column if your dataset uses a different country name column.
world["Country"] = world["NAME"]

merged = world.merge(
    df_clean,
    on="Country",
    how="left"
)

# -----------------------------------------
# Map 1: Average Temperature
# -----------------------------------------

fig, ax = plt.subplots(figsize=(15, 8))

merged.plot(
    column="Average Temperature",
    cmap="coolwarm",
    linewidth=0.5,
    edgecolor="black",
    legend=True,
    ax=ax,
    missing_kwds={
        "color": "lightgray",
        "label": "No Data"
    }
)

ax.set_title("Country-wise Average Temperature")
ax.set_axis_off()

plt.show()


# -----------------------------------------
# Map 2: CO2 Emissions
# -----------------------------------------

fig, ax = plt.subplots(figsize=(15, 8))

merged.plot(
    column="CO2 Emissions",
    cmap="Oranges",
    linewidth=0.5,
    edgecolor="black",
    legend=True,
    ax=ax,
    missing_kwds={
        "color": "lightgray",
        "label": "No Data"
    }
)

ax.set_title("Country-wise CO2 Emissions")
ax.set_axis_off()

plt.show()


# -----------------------------------------
# Map 3: Forest Area
# -----------------------------------------

fig, ax = plt.subplots(figsize=(15, 8))

merged.plot(
    column="Forest Area",
    cmap="Greens",
    linewidth=0.5,
    edgecolor="black",
    legend=True,
    ax=ax,
    missing_kwds={
        "color": "lightgray",
        "label": "No Data"
    }
)

ax.set_title("Country-wise Forest Area")
ax.set_axis_off()

plt.show()
 

2. Create a dataset containing information about different colleges.
Attributes: College Name, Placement %, Research Publications, Student Strength, Average Package Perform the following tasks:
a. Create a Treemap showing student distribution.
b. Generate a 3D Scatter Plot using Placement %, Publications, and Average Package.
c. Create a Heat Map for feature correlation.

 

Required Libraries

Install the required libraries if necessary:

pip install pandas matplotlib seaborn squarify
 
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import squarify

# -----------------------------------------
# Create College Dataset
# -----------------------------------------

data = {
"College Name": [
"ABC College",
"XYZ University",
"PQR Institute",
"LMN College",
"Sunrise University",
"Modern Institute",
"Global College",
"National Institute",
"City College",
"Tech University"
],

"Placement %": [
82, 91, 76, 88, 95,
79, 85, 93, 72, 90
],

"Research Publications": [
45, 85, 32, 68, 110,
40, 55, 95, 25, 78
],

"Student Strength": [
1800, 3200, 1500, 2400, 4000,
1700, 2200, 3500, 1200, 2800
],

"Average Package": [
5.2, 8.5, 4.8, 7.2, 10.5,
5.5, 6.5, 9.2, 4.2, 8.0
]
}

df = pd.DataFrame(data)

# Display dataset
print("College Dataset:")
print(df)

# Save dataset
df.to_csv("college_data.csv", index=False)


# =========================================
# a) TREEMAP - STUDENT DISTRIBUTION
# =========================================

plt.figure(figsize=(12, 7))

squarify.plot(
sizes=df["Student Strength"],
label=df["College Name"],
alpha=0.8
)

plt.title("Student Distribution Across Colleges")
plt.axis("off")

plt.show()


# =========================================
# b) 3D SCATTER PLOT
# =========================================

fig = plt.figure(figsize=(10, 7))

ax = fig.add_subplot(111, projection="3d")

scatter = ax.scatter(
df["Placement %"],
df["Research Publications"],
df["Average Package"],
s=80
)

# Add college names to points
for i in range(len(df)):
ax.text(
df["Placement %"][i],
df["Research Publications"][i],
df["Average Package"][i],
df["College Name"][i],
fontsize=8
)

ax.set_xlabel("Placement Percentage (%)")
ax.set_ylabel("Research Publications")
ax.set_zlabel("Average Package (LPA)")

ax.set_title(
"3D Scatter Plot of College Performance"
)

plt.tight_layout()
plt.show()


# =========================================
# c) CORRELATION HEAT MAP
# =========================================

# Select numerical columns
numerical_data = df[
[
"Placement %",
"Research Publications",
"Student Strength",
"Average Package"
]
]

# Calculate correlation
correlation = numerical_data.corr()

print("\nCorrelation Matrix:")
print(correlation)


# Generate heat map
plt.figure(figsize=(9, 7))

sns.heatmap(
correlation,
annot=True,
cmap="coolwarm",
fmt=".2f",
linewidths=0.5
)

plt.title("Correlation Heat Map of College Features")
plt.xlabel("Features")
plt.ylabel("Features")

plt.tight_layout()
plt.show() 

 

No comments:

Post a Comment