How to Use KDE Plot in Python: Simple Guide with Examples
To create a KDE plot in Python, use the
kdeplot function from the seaborn library, which visualizes the probability density of a dataset smoothly. Import seaborn, pass your data to kdeplot, and call plt.show() to display the plot.Syntax
The basic syntax for a KDE plot in Python using seaborn is:
seaborn.kdeplot(data, shade=False, bw_adjust=1, clip=None, ax=None)- data: The dataset to plot (list, array, or pandas Series).
- shade: If True, fills the area under the curve.
- bw_adjust: Adjusts the smoothness of the curve (higher is smoother).
- clip: Limits the range of the plot.
- ax: Matplotlib axis to plot on (optional).
python
import seaborn as sns import matplotlib.pyplot as plt sns.kdeplot(data=[1, 2, 3, 4, 5], shade=True) plt.show()
Example
This example shows how to create a KDE plot for a list of numbers and customize its appearance by shading the area under the curve and adjusting the bandwidth for smoothness.
python
import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Generate 100 random numbers from a normal distribution data = np.random.normal(loc=0, scale=1, size=100) # Create KDE plot with shaded area and smoother curve sns.kdeplot(data, shade=True, bw_adjust=0.5) plt.title('KDE Plot of Normal Distribution') plt.xlabel('Value') plt.ylabel('Density') plt.show()
Output
A smooth bell-shaped curve plot appears showing the density distribution of the data.
Common Pitfalls
Common mistakes when using kdeplot include:
- Passing empty or non-numeric data causes errors or empty plots.
- Not calling
plt.show()so the plot does not display. - Using very small datasets can produce noisy or misleading KDE curves.
- Confusing
shadewithfill(useshade=Trueto fill under the curve).
Always check your data and call plt.show() after plotting.
python
import seaborn as sns import matplotlib.pyplot as plt # Wrong: empty data sns.kdeplot([]) plt.show() # Right: valid numeric data sns.kdeplot([1, 2, 3, 4, 5], shade=True) plt.show()
Output
First plot shows no curve (empty), second plot shows a smooth KDE curve with shaded area.
Quick Reference
Remember these tips for KDE plots:
- Use
seaborn.kdeplot(data)to create the plot. - Set
shade=Trueto fill under the curve. - Adjust smoothness with
bw_adjust(default is 1). - Always call
plt.show()to display the plot. - Works best with numeric data and enough samples (usually 20+).
Key Takeaways
Use seaborn's kdeplot to create smooth density plots from numeric data.
Set shade=True to fill the area under the KDE curve for better visualization.
Call plt.show() after plotting to display the graph.
Avoid empty or very small datasets to get meaningful KDE plots.
Adjust bw_adjust to control the smoothness of the KDE curve.