Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to fill the area under a curve in a Seaborn distribution plot?
To fill the area under a curve in a Seaborn distribution plot, we can use displot() with the fill parameter or combine histplot() with matplotlib's fill_between() method for custom styling.
Method 1: Using displot() with fill Parameter
The simplest approach is to use Seaborn's built-in fill parameter ?
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
np.random.seed(42)
data = np.random.normal(50, 15, 1000)
# Create distribution plot with filled area
plt.figure(figsize=(8, 5))
sns.displot(data, kind="kde", fill=True, color="skyblue", alpha=0.7)
plt.title("Distribution Plot with Filled Area")
plt.show()
Method 2: Using histplot() with Custom Fill
For more control over the fill pattern, you can extract curve data and use fill_between() ?
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
np.random.seed(42)
data = np.random.normal(50, 15, 1000)
# Create the plot
plt.figure(figsize=(8, 5))
ax = sns.histplot(data, kde=True, stat="density", alpha=0.3, color="lightblue")
# Get the KDE line data
kde_line = ax.lines[0]
x_data = kde_line.get_xdata()
y_data = kde_line.get_ydata()
# Fill the area under the KDE curve
ax.fill_between(x_data, y_data, alpha=0.5, color="red", label="Filled Area")
ax.set_title("Custom Filled Distribution Plot")
ax.legend()
plt.show()
Method 3: Filling Specific Regions
You can also fill specific regions under the curve by setting conditions ?
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
np.random.seed(42)
data = np.random.normal(50, 15, 1000)
# Create the plot
plt.figure(figsize=(8, 5))
ax = sns.histplot(data, kde=True, stat="density", alpha=0.3)
# Get KDE line data
kde_line = ax.lines[0]
x_data = kde_line.get_xdata()
y_data = kde_line.get_ydata()
# Fill area for values greater than 60
mask = x_data >= 60
ax.fill_between(x_data, y_data, where=mask, alpha=0.6, color="orange",
label="Area where x ? 60")
ax.set_title("Filled Region Above Threshold")
ax.legend()
plt.show()
Comparison
| Method | Use Case | Complexity | Customization |
|---|---|---|---|
displot(fill=True) |
Simple full area fill | Low | Limited |
fill_between() |
Custom styling | Medium | High |
| Conditional fill | Specific regions | Medium | Very High |
Conclusion
Use displot(fill=True) for quick area fills. For advanced customization like partial fills or multiple colors, combine histplot() with fill_between() method.
Advertisements
