How to locate the median in a (Seaborn) KDE plot?

A Kernel Density Estimation (KDE) plot shows the probability density of data points. To locate and highlight the median in a Seaborn KDE plot, we can calculate the median value and draw a vertical line at that position.

Steps to Add Median Line

  • Create or load your dataset
  • Calculate the median using np.median()
  • Plot the KDE using sns.kdeplot()
  • Add a vertical line at the median using plt.axvline()

Example

Here's how to create a KDE plot with the median highlighted ?

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample data
data = np.random.randn(30)

# Calculate median
data_median = np.median(data)

# Create KDE plot
sns.kdeplot(x=data, fill=True, alpha=0.7, color='skyblue')

# Add vertical line at median
plt.axvline(data_median, color='red', linestyle='--', linewidth=2, label=f'Median: {data_median:.2f}')

# Add labels and legend
plt.xlabel('Data Values')
plt.ylabel('Density')
plt.title('KDE Plot with Median Line')
plt.legend()

plt.show()

Enhanced Example with Multiple Statistics

You can also add mean and other statistics for comparison ?

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# Create larger dataset
np.random.seed(42)  # For reproducible results
data = np.random.normal(10, 3, 1000)

# Calculate statistics
data_median = np.median(data)
data_mean = np.mean(data)

# Create KDE plot
plt.figure(figsize=(10, 6))
sns.kdeplot(x=data, fill=True, alpha=0.6, color='lightblue')

# Add vertical lines for median and mean
plt.axvline(data_median, color='red', linestyle='--', linewidth=2, 
           label=f'Median: {data_median:.2f}')
plt.axvline(data_mean, color='green', linestyle='--', linewidth=2, 
           label=f'Mean: {data_mean:.2f}')

# Formatting
plt.xlabel('Data Values')
plt.ylabel('Density')
plt.title('KDE Plot with Median and Mean Lines')
plt.legend()
plt.grid(True, alpha=0.3)

plt.show()

Key Points

  • fill=True replaces the deprecated shade=True parameter
  • axvline() draws a vertical line across the entire plot height
  • Use linestyle='--' to make the median line distinguishable
  • Adding labels and legends improves plot readability

Conclusion

Use np.median() to calculate the median and plt.axvline() to draw a vertical line at that position. This technique helps visualize where the median falls within the data distribution.

Updated on: 2026-03-25T21:27:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements