Data Visualization: lesson 3 of 3

Data Visualization

PATH 01MODULE 05LESSON 03 OF 03

Seaborn and Statistical Visualization

Use Seaborn to explore distributions, groups, relationships, and correlation patterns in tabular data.

Beginner16 min readdata-visualizationseabornstatisticscorrelation

Concept

Seaborn is a Python visualization library designed for statistical graphics and tabular data. It complements Matplotlib by making common plots concise and by working naturally with DataFrame column names. The examples below are Python code; the website does not execute or render their plots.

Why It Matters

Analysts often need to compare distributions across groups, inspect relationships, and look for patterns before modeling. Seaborn expresses these questions directly: choose a DataFrame, name columns, and optionally split the view by a meaningful category.

A Small Customer Dataset

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

customers = pd.DataFrame({
    "age": [24, 31, 38, 29, 45, 52],
    "annual_spend": [1200, 2100, 3300, 1800, 4100, 4600],
    "segment": ["Basic", "Basic", "Premium", "Basic", "Premium", "Premium"],
    "contract": ["Monthly", "Annual", "Annual", "Monthly", "Annual", "Monthly"],
    "churned": [1, 0, 0, 1, 0, 1],
})

Distributions and Groups

sns.histplot(data=customers, x="annual_spend", hue="segment", kde=True)
plt.title("Annual Spend by Customer Segment")
plt.show()

sns.boxplot(data=customers, x="segment", y="annual_spend")
plt.title("Spend Distribution by Segment")
plt.show()

The histogram would show how spending is distributed and how Basic and Premium customers contribute to that pattern. hue separates groups using color. The box plot would compare each segment's median, spread, and potential unusual values. With a very small dataset, these are illustrations rather than reliable population conclusions.

Relationships and Category Comparisons

sns.scatterplot(
    data=customers,
    x="age",
    y="annual_spend",
    hue="segment",
)
plt.title("Age and Annual Spend")
plt.show()

sns.barplot(data=customers, x="contract", y="churned")
plt.title("Observed Churn Rate by Contract")
plt.show()

The scatter plot places each customer by age and spend, with color indicating segment. It can suggest clusters, outliers, or a relationship worth investigating. The bar plot uses the average of the numeric churned column, so when 1 means churn and 0 means no churn, each bar represents the observed churn proportion. Always confirm how a target is encoded before interpreting an average this way.

Correlation Heatmaps

numeric_columns = ["age", "annual_spend", "churned"]
correlation = customers[numeric_columns].corr()

sns.heatmap(correlation, annot=True, cmap="vlag", center=0)
plt.title("Feature Correlations")
plt.show()

The expected heatmap colors a matrix of pairwise correlations. Values near +1 indicate a strong positive linear relationship, values near -1 indicate a strong negative linear relationship, and values near 0 indicate little linear relationship. Correlation does not prove causation, can miss curved relationships, and can be distorted by outliers or mixed groups.

Code Explanation

data=customers supplies the DataFrame, while x and y name columns. hue adds a group comparison without manually filtering separate DataFrames. sns.histplot, sns.boxplot, sns.scatterplot, and sns.barplot select chart types suited to distributions, spread, relationships, and category summaries. sns.heatmap visualizes a numeric matrix; annot=True writes compact values in its cells. Matplotlib calls can still add titles, labels, or layout adjustments.

Choosing the Right Approach

Use histplot for a numerical distribution, boxplot for distribution comparisons, scatterplot for two numerical variables, and barplot for a summarized numeric metric across categories. Use a heatmap only when the matrix is small enough to read and correlation is a meaningful question. Reserve hue for a small number of groups; too many colors make comparisons worse.

Failure Signals

Common Mistakes

  1. Treating a box plot as proof that an extreme value is an error.
  2. Using hue for many categories until colors and legends become unreadable.
  3. Interpreting a correlation heatmap as a causal explanation.
  4. Forgetting that a bar plot may display an aggregate rather than individual values.
  5. Comparing groups with tiny or very unequal sample sizes without showing the context.

Best Practices

Start with a clear question and verify the column types and meanings. Use titles and labels even when Seaborn infers names. Keep color consistent for a category across related charts, inspect sample sizes, and supplement an aggregate chart with a distribution plot when variation matters. Investigate notable patterns with data and domain context before recommending action.

Data Science Perspective

Seaborn is useful for the early visual checks that inform cleaning, feature review, segmentation, and introductory model diagnostics. A correlation heatmap may flag redundant features or a relationship to examine, but feature choice should also consider leakage, business meaning, and validation results.

Interview Perspective

Question: What does a correlation near zero mean? Answer: it suggests little linear relationship in the observed data; it does not prove the variables are unrelated. Follow-up: name two reasons correlation does not establish causation.

Practice Questions

  1. Which Seaborn chart would you use to compare salary distributions across departments?
  2. What does hue="segment" add to a spending histogram?
  3. A heatmap shows a high correlation between two features. What should you investigate before removing one?

Quick Quiz

  1. Which function creates a box plot? Answer: sns.boxplot().
  2. What do values near -1 in a correlation matrix indicate? Answer: a strong negative linear relationship.
  3. Does a correlation heatmap establish cause and effect? Answer: no.

Key Takeaway

Key Takeaways

Seaborn makes statistical visuals concise for DataFrames. Use histograms and box plots for distributions, scatter plots for relationships, bar plots for group summaries, and heatmaps for readable correlation matrices. Every plot still requires context and careful interpretation.

Next Lesson

Continue to Statistics & Probability to build the quantitative reasoning behind many visual summaries.

Finish this lesson on your terms

Mark it complete when you have worked through the material and are ready to move on.