Learning Density Plot Creation with Matplotlib and Seaborn


Creating a robust and informative density plot in Matplotlib is essential for visualizing the underlying distribution of continuous data. While Matplotlib provides the core framework, generating high-quality density estimates often requires leveraging the specialized capabilities of the Seaborn statistical visualization library. Seaborn offers the highly efficient and convenient kdeplot() function, which is the most recommended method for visualizing data distribution using Kernel Density Estimation (KDE). This powerful, non-parametric technique smooths discrete data points into a continuous curve, providing analysts with a clear visual representation of where the data is concentrated and identifying the shape of the population distribution.

import seaborn as sns

# Define the numerical dataset
data = [value1, value2, value3, ...]

# Create a default density plot of the data
sns.kdeplot(data)

The basic syntax above underscores the simplicity of generating a fundamental KDE plot. By simply passing your numerical dataset to sns.kdeplot(), you delegate the complex statistical tasks to Seaborn, which automatically calculates the optimal bandwidth and renders the continuous distribution estimate. The following sections will provide practical, detailed examples demonstrating how to implement this foundational function and how to customize its critical parameters—such as bandwidth and aesthetics—for conducting effective and visually compelling data analysis.

Setting Up the Environment and Understanding the Core Concept

Before attempting any plotting, it is crucial to ensure that both the foundational library, Matplotlib, and the specialized statistical library, Seaborn, are correctly installed and configured within your Python environment. Seaborn is explicitly designed to build upon and enhance Matplotlib’s framework, simplifying the creation of complex statistical graphics. The fundamental purpose of a density plot is to estimate the underlying Probability Density Function (PDF) of a random variable, offering a non-parametric view that avoids assumptions about the data’s distributional shape (unlike, for example, a histogram).

The standard implementation requires importing the necessary libraries (conventionally imported as sns and plt, although only sns is strictly necessary for the examples below) and defining the numerical dataset intended for analysis. Although in most professional data science contexts, this data would be derived from a specialized structure like a Pandas DataFrame, we utilize a basic Python list for demonstration purposes. This introductory setup showcases the robust default settings applied by Seaborn, which are generally sufficient and highly reliable for initial exploratory data analysis (EDA).

The process of Kernel Density Estimation involves placing a weighted kernel (a smoothing function, often Gaussian) over every data point and then summing these kernels to produce the final continuous curve. The resulting plot is superior to a histogram in many cases because it removes the visual artifacts caused by arbitrary bin choices, presenting a smoother, more accurate representation of the data’s true density.

Example 1: Generating a Standard Density Plot

This first example illustrates the most straightforward and common application of the kdeplot() function. We begin by defining a small, representative set of numerical data points and then visualize their distribution using the default parameters provided by Seaborn. Notice how the resulting curve smoothly represents the relative frequency of values, reaching its peak precisely where the data concentration is highest. Seaborn’s default settings are meticulously chosen to strike an effective balance between the smoothness of the curve and its fidelity to the underlying structure of the input data.

import seaborn as sns

# Define the sample data for visualization
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 12, 12, 13, 15, 16]

# Create the density plot using default settings
sns.kdeplot(data)

density plot in seaborn

Interpreting the axes of this visualization is crucial for deriving meaningful insights. The x-axis simply plots the range of data values present in our input list, spanning from the minimum to the maximum observed values. The y-axis, however, displays the corresponding probability density estimates. It is fundamentally important to grasp that these density values are not probabilities themselves. Instead, the area under the curve between any two points represents the probability that a data point falls within that specific interval. Consequently, a fundamental property of all density plots is that the total area under the entire curve must always sum precisely to 1.0, representing 100% of the distribution.

Example 2: Controlling Plot Smoothness via Bandwidth Selection

A central parameter in Kernel Density Estimation is the bandwidth (often mathematically denoted as ‘h’). This single value critically determines the level of smoothness applied to the resulting density curve and is controlled in Seaborn’s kdeplot() using the bw_method argument. The bandwidth essentially dictates the width of the kernel function used to smooth and aggregate the data points. Selecting the appropriate bandwidth involves navigating the crucial statistical trade-off between bias and variance: if the bandwidth is too small, the plot appears overly noisy and spiky (high variance); if it is too large, the plot becomes overly smooth, potentially obscuring important features of the distribution (high bias).

By default, Seaborn employs sophisticated statistical methods (such as Scott’s Rule or Silverman’s Rule) to automatically select an empirically optimal bandwidth. However, data analysts frequently require manual control over this parameter to either highlight specific characteristics of the distribution or to facilitate meaningful comparisons across different datasets. We will now explore how adjusting the bw_method parameter significantly impacts the resulting visualization, starting with a low value to examine fine-grained detail.

Setting a relatively low numerical value for bw_method results in a less smoothed, more “wiggly” plot. This outcome occurs because a smaller bandwidth assigns less weight to distant data points when calculating the density estimate at any given location. While this can be highly advantageous for identifying localized peaks, multimodality, or subtle fluctuations in the data, it also runs the risk of introducing visual noise or artifacts that may not truly represent the underlying population distribution, reflecting high variance in the estimate.

import seaborn as sns

# Define the sample data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 12, 12, 13, 15, 16]

# Create density plot with a low bw_method value (.3) for less smoothing
sns.kdeplot(data, bw_method = .3)

Conversely, applying a higher numerical value for bw_method forces the density plot to become significantly smoother. A large bandwidth effectively averages the data over a much wider range, substantially reducing variance but simultaneously increasing bias. This means that while the plot captures the overall, generalized shape of the distribution, it is highly likely to obscure subtle but potentially important details, such as minor modes or sharp transitions. This highly smoothed representation is often preferred when presenting data to a non-technical audience or when the primary objective is to capture the macro-level structure of the data rather than microscopic fluctuations. Analysts must always justify their bandwidth choice based on the underlying scientific question they are attempting to address.

import seaborn as sns

# Define the sample data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 12, 12, 13, 15, 16]

# Create density plot with a high bw_method value (.8) for maximum smoothing
sns.kdeplot(data, bw_method = .8)

Example 3: Advanced Aesthetic and Visual Customization

Beyond ensuring statistical accuracy, the presentation quality of a plot is absolutely vital for effective data communication. Seaborn’s kdeplot() function provides numerous aesthetic arguments, many of which are inherited directly from Matplotlib, allowing for deep and precise customization of the plot’s visual style. These options include controlling the primary color, transparency (opacity), and line thickness, ensuring that the resulting visualization is not only statistically accurate but also visually appealing, accessible, and easy for any audience to interpret quickly.

Understanding these key customization parameters allows analysts to tailor the output to specific reporting requirements:

  • color: This sets the primary color utilized for both the density contour line and the shaded fill area underneath the curve.
  • fill: When set to True, this parameter instructs Seaborn to shade the area underneath the density curve. Shading significantly enhances the readability and visual impact of the density plot, making the distribution shape more immediately apparent.
  • alpha: This controls the transparency (or opacity) of the fill area. Values must range from 0 (completely transparent) to 1 (fully opaque). This parameter is particularly useful when overlaying multiple distributions.
  • linewidth: This adjusts the thickness of the outer contour line. Setting it explicitly to 0 removes the boundary line entirely, a technique often used for a cleaner, modern look when the focus is purely on the filled area.

The following code demonstrates the application of these customization options, resulting in a highly tailored plot. Here, we emphasize the filled area using a distinct red color, apply a measured transparency level, and explicitly remove the outer boundary line for a sleek, contemporary visualization style that focuses attention squarely on the distribution’s shape.

import seaborn as sns

# Define the sample data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 12, 12, 13, 15, 16]

# Create density plot with advanced aesthetics (red fill, transparent, no line)
sns.kdeplot(data, color='red', fill=True, alpha=.3, linewidth=0)

Summary of Best Practices and Further Resources

Density plots are invaluable, flexible tools for intuitively visualizing the shape, central tendency, and spread of continuous data distributions. When constructing these plots using Seaborn’s kdeplot() function, remember that the choice of the bw_method is the single most critical decision. This parameter directly dictates the visual interpretation of your data by controlling the fundamental bias-variance trade-off inherent in the KDE estimate. A best practice involves experimenting with a range of bandwidth values—both lower and higher than the default—to confirm whether apparent distributional features, such as multiple peaks, are robust characteristics of the data or merely artifacts introduced by the smoothing process.

For maximum clarity and professional presentation, always adhere to core visualization principles: properly label your axes (especially clarifying that the Y-axis represents density, not frequency counts) and consider consistently using the fill=True parameter to clearly delineate the area under the curve. When comparing multiple distributions simultaneously—for instance, by using the hue argument or layering plots—employing distinct colors combined with appropriate alpha levels ensures that overlapping densities remain distinguishable without creating visual clutter. Mastery of these plotting techniques allows for the rapid production of professional-grade statistical graphics that effectively communicate complex data distributions, forming the foundation of robust data exploration.

For further documentation, detailed statistical methodologies, and complex usage scenarios involving multidimensional density estimates, please consult the following official and authoritative resources:

Cite this article

Mohammed looti (2025). Learning Density Plot Creation with Matplotlib and Seaborn. PSYCHOLOGICAL STATISTICS. Retrieved from https://statistics.arabpsychology.com/create-a-density-plot-in-matplotlib-with-examples/

Mohammed looti. "Learning Density Plot Creation with Matplotlib and Seaborn." PSYCHOLOGICAL STATISTICS, 3 Nov. 2025, https://statistics.arabpsychology.com/create-a-density-plot-in-matplotlib-with-examples/.

Mohammed looti. "Learning Density Plot Creation with Matplotlib and Seaborn." PSYCHOLOGICAL STATISTICS, 2025. https://statistics.arabpsychology.com/create-a-density-plot-in-matplotlib-with-examples/.

Mohammed looti (2025) 'Learning Density Plot Creation with Matplotlib and Seaborn', PSYCHOLOGICAL STATISTICS. Available at: https://statistics.arabpsychology.com/create-a-density-plot-in-matplotlib-with-examples/.

[1] Mohammed looti, "Learning Density Plot Creation with Matplotlib and Seaborn," PSYCHOLOGICAL STATISTICS, vol. X, no. Y, ص Z-Z, November, 2025.

Mohammed looti. Learning Density Plot Creation with Matplotlib and Seaborn. PSYCHOLOGICAL STATISTICS. 2025;vol(issue):pages.

Download Post (.PDF)
Scroll to Top