Bird
Raised Fist0
Matplotlibdata~20 mins

KDE overlay concept in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
KDE Overlay Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this KDE overlay plot code?
Look at the code below that creates two KDE plots overlaid on the same axes. What will the plot show?
Matplotlib
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

np.random.seed(0)
data1 = np.random.normal(0, 1, 100)
data2 = np.random.normal(2, 1, 100)

kde1 = gaussian_kde(data1)
kde2 = gaussian_kde(data2)

x = np.linspace(-4, 6, 200)

plt.plot(x, kde1(x), label='Data 1')
plt.plot(x, kde2(x), label='Data 2')
plt.legend()
plt.show()
ATwo smooth curves showing peaks near 0 and 2, overlapping slightly
BTwo flat lines with no peaks
CA single curve with one peak at 1
DTwo curves with peaks at -2 and 4
Attempts:
2 left
💡 Hint
Think about where the normal distributions are centered and how KDE estimates density.
❓ data_output
intermediate
1:30remaining
How many peaks are visible in the KDE overlay plot?
Given two datasets with different centers, when overlaid using KDE plots, how many distinct peaks should appear?
Matplotlib
import numpy as np
from scipy.stats import gaussian_kde

np.random.seed(1)
data1 = np.random.normal(-1, 0.5, 150)
data2 = np.random.normal(3, 0.5, 150)

kde1 = gaussian_kde(data1)
kde2 = gaussian_kde(data2)

x = np.linspace(-3, 5, 300)

kde_values1 = kde1(x)
kde_values2 = kde2(x)

combined = kde_values1 + kde_values2

peaks = ((combined[1:-1] > combined[:-2]) & (combined[1:-1] > combined[2:])).sum()
A1
B0
C3
D2
Attempts:
2 left
💡 Hint
Each dataset is centered far apart, so each should create a peak.
❓ visualization
advanced
2:30remaining
Which option correctly overlays KDE plots with different bandwidths?
You want to overlay KDE plots of two datasets but use a smaller bandwidth for the second dataset to get a sharper curve. Which code snippet does this correctly?
A
kde1 = gaussian_kde(data1, bw_method='scott')
kde2 = gaussian_kde(data2, bw_method='silverman')
B
kde1 = gaussian_kde(data1, bw_method=0.1)
kde2 = gaussian_kde(data2, bw_method=0.5)
C
kde1 = gaussian_kde(data1, bw_method=0.5)
kde2 = gaussian_kde(data2, bw_method=0.1)
D
kde1 = gaussian_kde(data1)
kde2 = gaussian_kde(data2, bw_method=0.1)
Attempts:
2 left
💡 Hint
Smaller bandwidth means sharper peaks. Assign smaller bandwidth to second dataset.
🔧 Debug
advanced
2:00remaining
What error does this KDE overlay code raise?
This code tries to overlay KDE plots but raises an error. What is the error?
Matplotlib
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

np.random.seed(0)
data1 = np.random.normal(0, 1, 100)
data2 = []

kde1 = gaussian_kde(data1)
kde2 = gaussian_kde(data2)

x = np.linspace(-4, 4, 100)

plt.plot(x, kde1(x), label='Data 1')
plt.plot(x, kde2(x), label='Data 2')
plt.legend()
plt.show()
ATypeError: 'list' object is not callable
BValueError: `dataset` input should have shape (n, m) with n>1
CNameError: name 'gaussian_kde' is not defined
DIndexError: index out of range
Attempts:
2 left
💡 Hint
Check the shape and content of data2 before passing to gaussian_kde.
🚀 Application
expert
3:00remaining
How to combine and visualize KDE overlays for three datasets with different colors and transparency?
You have three datasets and want to plot their KDE overlays on the same plot. You want each KDE curve to have a distinct color and some transparency so overlaps are visible. Which code snippet achieves this?
A
plt.plot(x, kde1(x), color='red', alpha=0.5)
plt.plot(x, kde2(x), color='green', alpha=0.5)
plt.plot(x, kde3(x), color='blue', alpha=0.5)
B
plt.plot(x, kde1(x), alpha=0.5)
plt.plot(x, kde2(x), alpha=0.5)
plt.plot(x, kde3(x), alpha=0.5)
C
plt.plot(x, kde1(x), color='red')
plt.plot(x, kde2(x), color='green')
plt.plot(x, kde3(x), color='blue')
D
plt.plot(x, kde1(x), color='red', alpha=1)
plt.plot(x, kde2(x), color='red', alpha=0.5)
plt.plot(x, kde3(x), color='red', alpha=0.3)
Attempts:
2 left
💡 Hint
Use both color and alpha parameters in plt.plot for distinct colors and transparency.

Practice

(1/5)
1. What does a KDE overlay plot primarily help you understand when comparing multiple groups?
easy
A. How the data distributions overlap and differ smoothly
B. The exact count of data points in each group
C. The median value of each group only
D. The correlation between two variables

Solution

  1. Step 1: Understand KDE overlay purpose

    KDE overlay plots show smooth curves representing data distributions for groups.
  2. Step 2: Compare what KDE overlay reveals

    It highlights how distributions overlap or differ, not exact counts or medians.
  3. Final Answer:

    How the data distributions overlap and differ smoothly -> Option A
  4. Quick Check:

    KDE overlay = smooth distribution comparison [OK]
Hint: KDE overlay shows smooth curves, not counts or single values [OK]
Common Mistakes:
  • Confusing KDE overlay with bar charts showing counts
  • Thinking KDE overlay shows only median or mean
  • Assuming KDE overlay shows correlation
2. Which of the following is the correct way to plot KDE overlays for two groups using seaborn?
easy
A. sns.kdeplot(data=df, x='value', group='group')
B. sns.kdeplot(data=df, y='value', color='group')
C. sns.kdeplot(data=df, x='value', hue='group', fill=True)
D. sns.kdeplot(data=df, x='value', label='group')

Solution

  1. Step 1: Identify seaborn syntax for KDE overlays

    Use hue to separate groups and fill=True to shade areas.
  2. Step 2: Check each option

    sns.kdeplot(data=df, x='value', hue='group', fill=True) uses correct parameters: hue='group' and fill=True. Others misuse parameters or omit grouping.
  3. Final Answer:

    sns.kdeplot(data=df, x='value', hue='group', fill=True) -> Option C
  4. Quick Check:

    Use hue for groups and fill for shading [OK]
Hint: Use hue=group and fill=True for KDE overlays in seaborn [OK]
Common Mistakes:
  • Using 'group' instead of 'hue' parameter
  • Confusing x and y parameters
  • Omitting fill=True for shaded KDE
3. Given the code below, what will the plot show?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

data = pd.DataFrame({
  'score': [1, 2, 2, 3, 4, 5, 5, 6, 7, 8],
  'group': ['A', 'A', 'B', 'B', 'A', 'B', 'A', 'B', 'A', 'B']
})
sns.kdeplot(data=data, x='score', hue='group', fill=True)
plt.show()
medium
A. Two smooth curves showing score distributions for groups A and B with shaded areas
B. A bar chart showing counts of scores for groups A and B
C. A scatter plot of scores colored by group
D. A line plot connecting scores in order for each group

Solution

  1. Step 1: Understand sns.kdeplot with hue and fill

    The code plots kernel density estimates for 'score' by 'group' with shaded areas.
  2. Step 2: Identify plot type from code

    It produces smooth curves (KDE) for groups A and B, not bars, scatter, or line plots.
  3. Final Answer:

    Two smooth curves showing score distributions for groups A and B with shaded areas -> Option A
  4. Quick Check:

    kdeplot with hue and fill = smooth shaded curves [OK]
Hint: kdeplot with hue and fill shows smooth shaded group distributions [OK]
Common Mistakes:
  • Confusing KDE plot with bar or scatter plots
  • Expecting raw data points instead of smooth curves
  • Ignoring the fill parameter effect
4. The following code throws an error. What is the most likely cause?
import seaborn as sns
sns.kdeplot(data=df, x='value', hue='group', fill='yes')
medium
A. The data parameter cannot be a DataFrame
B. The fill parameter should be a boolean, not a string
C. The x parameter should be a list of columns
D. The hue parameter must be a list, not a string

Solution

  1. Step 1: Check fill parameter type

    In seaborn's kdeplot, fill expects True or False, not a string like 'yes'.
  2. Step 2: Validate other parameters

    Hue accepts a column name string, x accepts a column name string, data accepts DataFrame. So these are correct.
  3. Final Answer:

    The fill parameter should be a boolean, not a string -> Option B
  4. Quick Check:

    fill=True/False, not 'yes' [OK]
Hint: fill must be True or False, never a string [OK]
Common Mistakes:
  • Passing 'yes' or 'no' as fill instead of True/False
  • Misunderstanding hue parameter type
  • Thinking data can't be a DataFrame
5. You want to compare the distribution of exam scores for three classes (X, Y, Z) using KDE overlays. Which approach best ensures clear visual comparison?
hard
A. Plot a single KDE curve for all classes combined without grouping
B. Plot histograms for each class on separate subplots without KDE
C. Plot KDE overlays but use the same color for all classes without labels
D. Plot KDE overlays with distinct colors, use hue='class', and add fill=True with transparency

Solution

  1. Step 1: Identify best way to compare multiple groups with KDE

    Using hue='class' separates groups, distinct colors differentiate them, and fill=True with transparency helps see overlaps.
  2. Step 2: Evaluate other options

    Separate histograms lose overlay comparison, single KDE hides group differences, same color without labels causes confusion.
  3. Final Answer:

    Plot KDE overlays with distinct colors, use hue='class', and add fill=True with transparency -> Option D
  4. Quick Check:

    Distinct colors + hue + fill = clear KDE overlay [OK]
Hint: Use hue, distinct colors, and fill with transparency for clarity [OK]
Common Mistakes:
  • Plotting combined KDE without group separation
  • Using same color for all groups causing confusion
  • Not using fill or transparency to show overlaps
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard