Skip to main content

Set A - Question 2

2. a) Consider the following dataset representing study hours and examination marks:

Assume: study_hours = [2, 4, 6, 8, 10] marks = [40, 55, 75, 85, 95]

Using Python visualization techniques: i. Create a scatter plot showing the relationship between study hours and marks. ii. Add a suitable title, X-axis label, and Y-axis label. iii. Interpret the relationship between study hours and marks from the plot. iv. Explain why a scatter plot is appropriate for this dataset. v. State one other visualization that could be used to analyze the distribution of marks.

Answer

i & ii. Python Code for Custom Scatter Plot

import matplotlib.pyplot as plt

# Dataset
study_hours = [2, 4, 6, 8, 10]
marks = [40, 55, 75, 85, 95]

# i. Create scatter plot with customized styling
plt.scatter(study_hours, marks, color='crimson', marker='o', s=100, edgecolor='black', label='Students')

# ii. Add labels and titles
plt.title('Relationship Between Study Hours and Exam Marks', fontsize=12, fontweight='bold', pad=12)
plt.xlabel('Study Hours', fontsize=10)
plt.ylabel('Examination Marks (%)', fontsize=10)

plt.show()

iii. Interpretation of the Relationship

There is a strong positive linear relationship between study hours and examination marks. As study hours increase, exam marks increase consistently. For instance, studying for 2 hours yields 40 marks, while 10 hours of study results in 95 marks.

iv. Why a Scatter Plot is Appropriate

A scatter plot is highly appropriate because it maps two continuous numeric variables onto Cartesian coordinates (X,YX, Y), making it easy to identify correlation, direction of trends, and potential outliers.

v. Alternative Visualization for Distribution of Marks

A Histogram or a Box-and-Whisker Plot could be used to analyze the distribution, dispersion, and spread of the examination marks alone.


2. b) Explain Exploratory Data Analysis (EDA). Discuss univariate, bivariate, and multivariate analysis with suitable techniques and examples.

Answer

What is Exploratory Data Analysis (EDA)?

Exploratory Data Analysis (EDA) is the process of examining and visualising datasets to summarize their core characteristics, detect anomalies/outliers, understand structural details, and extract patterns before applying formal modeling.

Types of Data Analysis in EDA

  1. Univariate Analysis

    • Definition: Analyzing one single variable at a time to understand its distribution and spread.
    • Techniques: Histograms, Box plots, Bar charts (for counts); calculating Mean, Median, Mode, Standard Deviation.
    • Example: Finding the average salary of employees in an organization.
  2. Bivariate Analysis

    • Definition: Analyzing the relationship or correlation between two separate variables simultaneously.
    • Techniques: Scatter plots (numerical vs numerical), Grouped Box plots (categorical vs numerical), Correlation coefficient (Pearson's rr).
    • Example: Plotting weight (XX) against height (YY) to analyze the correlation.
  3. Multivariate Analysis

    • Definition: Examining interactions and relationships among three or more variables at the same time.
    • Techniques: Correlation Heatmaps, Pair Plots, 3D Scatter Plots, and principal component analysis (PCA).
    • Example: Analyzing how House Price (YY) relates to Square Footage (X1X_1), Number of Bedrooms (X2X_2), and Neighborhood Age (X3X_3) simultaneously.

2. c) Write a Python program that demonstrates key concepts from the following topics: Python data structures, functions, and data analysis using libraries like NumPy, Pandas, and Matplotlib. The program should:

i. Define a function called analyze_sales_data() that accepts a list of sales figures (integers) and performs the following tasks: Calculate the total, maximum, minimum, and average sales from the list. ii. Create a NumPy array from the given sales figures and perform basic statistical operations on the array (sum, mean, median). iii. Convert the NumPy array into a Pandas DataFrame and create an additional column for "Region" which is randomly chosen from ['North', 'South', 'East', 'West']. iv. Plot a bar chart of total sales per region using Matplotlib.

Answer

Here is the complete, modular Python program:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

# Seed for reproducibility
random.seed(42)
np.random.seed(42)

# i. Define analyze_sales_data() function
def analyze_sales_data(sales_list):
"""
Calculates key metrics from a list of sales figures.
"""
total = sum(sales_list)
maximum = max(sales_list)
minimum = min(sales_list)
average = total / len(sales_list) if len(sales_list) > 0 else 0

print("--- i. Python List Analysis ---")
print(f"Total Sales: {total}")
print(f"Max Sales: {maximum}")
print(f"Min Sales: {minimum}")
print(f"Avg Sales: {average:.2f}\n")

return total, maximum, minimum, average

# Input Sales list
sales_figures = [1200, 1500, 800, 3200, 4500, 1100, 2100, 1900, 4000, 2500, 3100, 1600]

# Run Part i
analyze_sales_data(sales_figures)

# ii. NumPy Array Operations
sales_arr = np.array(sales_figures)
arr_sum = np.sum(sales_arr)
arr_mean = np.mean(sales_arr)
arr_median = np.median(sales_arr)

print("--- ii. NumPy Statistical Operations ---")
print(f"Sum: {arr_sum}")
print(f"Mean: {arr_mean:.2f}")
print(f"Median: {arr_median}\n")

# iii. Convert to Pandas DataFrame & Add Random 'Region' Column
regions = ['North', 'South', 'East', 'West']
df = pd.DataFrame(sales_arr, columns=["Sales"])

# Generate random region choices matching DataFrame length
df["Region"] = [random.choice(regions) for _ in range(len(df))]

print("--- iii. Pandas DataFrame ---")
print(df.head(10))
print()

# iv. Plot Bar Chart of Total Sales per Region
region_totals = df.groupby("Region")["Sales"].sum()

plt.bar(region_totals.index, region_totals.values, color='skyblue')
plt.title('Total Sales per Region')
plt.xlabel('Region')
plt.ylabel('Total Sales ($)')
plt.show()