Following our study of location, variability, shape, heterogeneity, and concentration, we now explore an additional dimension of exploratory data analysis: correlation. While previous chapters focused primarily on univariate descriptions or subgroup comparisons, correlation analysis enables the exploration of relationships among numerical variables.
In general terms, correlation addresses key analytical questions:
Do sales increase when product list price increases?
Is there an association between product visibility and sales?
Is product weight associated with other quantitative variables?
Are observed associations linear, monotonic, or practically non-existent?
This chapter focuses on evaluating relationships among numerical variables in the BigMart Sales dataset, with particular emphasis on our target variable:
\[
\texttt{Item\_Outlet\_Sales}.
\]
Beyond calculating correlation coefficients, we construct visual representations to aid in interpreting associations within an EDA framework. The objective is not to establish causality, but to detect dependence patterns, redundancy, or approximate independence that enhance our understanding of the dataset.
Chapter Objectives
Upon completing this chapter, the reader should be able to:
distinguish between positive, negative, and near-zero correlation;
interpret the magnitude and sign of a correlation coefficient;
compare Pearson and Spearman correlation metrics;
build a correlation matrix for numerical variables;
integrate correlation findings into a comprehensive analytics dashboard.
Data Loading and Preparation
import numpy as npimport pandas as pdimport plotly.express as pximport plotly.graph_objects as goDATA_PATH ="../../data/bigmart_sales.csv"df = pd.read_csv(DATA_PATH)if"Item_Fat_Content"in df.columns: df["Item_Fat_Content"] = ( df["Item_Fat_Content"] .replace({"LF": "Low Fat","low fat": "Low Fat","reg": "Regular" }) )df.head()
Item_Identifier
Item_Weight
Item_Fat_Content
Item_Visibility
Item_Type
Item_MRP
Outlet_Identifier
Outlet_Establishment_Year
Outlet_Size
Outlet_Location_Type
Outlet_Type
Item_Outlet_Sales
0
FDA15
9.30
Low Fat
0.016047
Dairy
249.8092
OUT049
1999
Medium
Tier 1
Supermarket Type1
3735.1380
1
DRC01
5.92
Regular
0.019278
Soft Drinks
48.2692
OUT018
2009
Medium
Tier 3
Supermarket Type2
443.4228
2
FDN15
17.50
Low Fat
0.016760
Meat
141.6180
OUT049
1999
Medium
Tier 1
Supermarket Type1
2097.2700
3
FDX07
19.20
Regular
0.000000
Fruits and Vegetables
182.0950
OUT010
1998
NaN
Tier 3
Grocery Store
732.3800
4
NCD19
8.93
Low Fat
0.000000
Household
53.8614
OUT013
1987
High
Tier 3
Supermarket Type1
994.7052
To examine correlation, we first isolate numerical features.
This matrix provides a quick overview of linear associations. Key observations include:
features showing strong associations with Item_Outlet_Sales;
pairs of predictor features exhibiting high collinearity;
overall prevalence of weak, moderate, or strong relationships.
In BigMart Sales, Item_MRP consistently exhibits a clear positive linear association with sales, whereas other numerical features display weak correlation.
Spearman Correlation
To contrast with Pearson metrics, we compute the Spearman rank correlation matrix.
Similar Pearson and Spearman coefficients reflect an approximately linear or stable monotonic relationship. When Spearman significantly exceeds Pearson, non-linear monotonicity or outlier sensitivity is indicated.
We can compare both metrics focused on our target variable.
target ="Item_Outlet_Sales"if target in num_df.columns: corr_compare = pd.DataFrame({"Pearson": corr_pearson[target],"Spearman": corr_spearman[target] }).sort_values(by="Pearson", ascending=False) corr_compareelse:print(f"Variable {target} is not present in numerical columns.")
Target Variable Correlations
We rank numerical features by their correlation with Item_Outlet_Sales.
if target in num_df.columns: sales_corr = ( corr_pearson[target] .drop(labels=[target], errors="ignore") .sort_values(ascending=False) .reset_index() ) sales_corr.columns = ["Variable", "Pearson_Correlation"] sales_corr
if target in num_df.columns: fig = px.bar( sales_corr, x="Variable", y="Pearson_Correlation", title="Pearson Correlation with Item_Outlet_Sales", labels={"Pearson_Correlation": "Correlation", "Variable": "Variable"} ) fig.update_layout(xaxis_tickangle=-30) fig.show()
Analytical Commentary
A moderate positive correlation between Item_MRP and Item_Outlet_Sales indicates that higher list price items tend to generate higher monetary revenue, though this does not imply that raising prices directly causes sales volume growth.
Scatter Plots
Scatter plots reveal structural nuances hidden within correlation matrices.
Sales vs. Maximum Retail Price (MRP)
if {"Item_MRP", "Item_Outlet_Sales"}.issubset(df.columns): fig = px.scatter( df, x="Item_MRP", y="Item_Outlet_Sales", opacity=0.5, title="Relationship Between Item_MRP and Item_Outlet_Sales", trendline="ols" ) fig.show()
Sales vs. Visibility
if {"Item_Visibility", "Item_Outlet_Sales"}.issubset(df.columns): fig = px.scatter( df, x="Item_Visibility", y="Item_Outlet_Sales", opacity=0.5, title="Relationship Between Item_Visibility and Item_Outlet_Sales", trendline="ols" ) fig.show()
Sales vs. Weight
if {"Item_Weight", "Item_Outlet_Sales"}.issubset(df.columns): fig = px.scatter( df, x="Item_Weight", y="Item_Outlet_Sales", opacity=0.5, title="Relationship Between Item_Weight and Item_Outlet_Sales", trendline="ols" ) fig.show()
What to Inspect in Scatter Plots
Scatter plots address structural questions:
Does the relationship appear linear?
Are clusters or sub-groups present?
Do outliers distort the correlation slope?
Does variance increase with magnitude (heteroscedasticity)?
Are non-linear boundaries visible?
Subgroup Correlation Analysis
Evaluating whether correlation metrics vary across store formats (Outlet_Type) connects correlation to heterogeneity analysis.
Example: Item_MRP vs. Sales Correlation by Outlet Type
if {"Outlet_Type", "Item_MRP", "Item_Outlet_Sales"}.issubset(df.columns): fig = px.bar( corr_by_outlet, x="Outlet_Type", y="MRP_Sales_Pearson_Corr", title="MRP vs. Sales Correlation by Outlet Type", labels={"Outlet_Type": "Outlet Type","MRP_Sales_Pearson_Corr": "Pearson Correlation" } ) fig.update_layout(xaxis_tickangle=-20) fig.show()
Reading
When correlation strength shifts significantly across sub-populations, global correlation coefficients obscure segment-specific dynamics.
Summary Association Table
We compile a summary table of key feature correlations relative to Item_Outlet_Sales.
if target in num_df.columns: corr_summary = pd.DataFrame({"Variable": [c for c in num_df.columns if c != target],"Pearson": [corr_pearson.loc[c, target] for c in num_df.columns if c != target],"Spearman": [corr_spearman.loc[c, target] for c in num_df.columns if c != target] }).sort_values(by="Pearson", ascending=False) corr_summary
We can append qualitative strength labels for clear reporting:
def strength_label(r): a =abs(r)if a <0.10:return"Very Weak"elif a <0.30:return"Weak"elif a <0.50:return"Moderate"elif a <0.70:return"Strong"else:return"Very Strong"if target in num_df.columns: corr_summary_labeled = corr_summary.copy() corr_summary_labeled["Pearson_Strength"] = corr_summary_labeled["Pearson"].apply(strength_label) corr_summary_labeled["Spearman_Strength"] = corr_summary_labeled["Spearman"].apply(strength_label) corr_summary_labeled
Correlation Mini-Dashboard
Correlation KPIs
if target in num_df.columns: strongest_var = corr_summary.iloc[0]["Variable"] iflen(corr_summary) >0else np.nan strongest_corr = corr_summary.iloc[0]["Pearson"] iflen(corr_summary) >0else np.nan corr_kpis = pd.DataFrame({"Indicator": ["Number of numerical variables","Most correlated variable with sales","Associated Pearson correlation","Associated Spearman correlation" ],"Value": [ num_df.shape[1], strongest_var,round(strongest_corr, 4) if pd.notnull(strongest_corr) else np.nan,round( corr_summary.loc[corr_summary["Variable"] == strongest_var, "Spearman"].iloc[0], 4 ) if pd.notnull(strongest_var) andlen(corr_summary) >0else np.nan ] }) corr_kpis
Final Discussion
Correlation analysis expands univariate EDA into bivariate feature interaction. In BigMart Sales, this dimension identifies numerical features displaying meaningful associations with sales volume.
Always combine numerical correlation matrices with scatter plots to verify linearity, segment clusters, and outlier influence.
Suggested Exercises
Compute correlation matrices separately for each store format (Outlet_Type) and compare against global metrics.
Calculate correlation matrices across product categories and document key differences.
Determine whether a log transformation of Item_Outlet_Sales alters linear correlation metrics.
Identify a variable pair exhibiting near-zero linear correlation whose scatter plot reveals non-linear structure.