13.2 C
London
Tuesday, July 2, 2024
HomePythonMatplotlib in PythonHow to Create a Density Plot in Matplotlib (With Examples)

How to Create a Density Plot in Matplotlib (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

The easiest way to create a density plot in Matplotlib is to use the kdeplot() function from the seaborn visualization library:

import seaborn as sns

#define data
data = [value1, value2, value3, ...]

#create density plot of data
sns.kdeplot(data)

The following examples show how to use this function in practice.

Example 1: Create Basic Density Plot

The following code shows how to create a basic density plot in seaborn:

import seaborn as sns

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

#create density plot of data
sns.kdeplot(data)

density plot in seaborn

The x-axis shows the data values and the y-axis shows the corresponding probability density values.

Example 2: Adjust Smoothness of Density Plot

You can use the bw_method argument to adjust the smoothness of the density plot. Lower values lead to a more “wiggly” plot.

import seaborn as sns

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

#create density plot of data with low bw_method value
sns.kdeplot(data, bw_method = .3)

Conversely, higher values for bw_method lead to a smoother plot:

import seaborn as sns

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

#create density plot of data with high bw_method value
sns.kdeplot(data, bw_method = .8)

Example 3: Customize Density Plot

You can also customize the color and style of the density plot:

import seaborn as sns

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

#create density plot of data with high bw_method value
sns.kdeplot(data, color='red', fill=True, alpha=.3, linewidth=0)

Additional Resources

An Introduction to Density Curves
How to Plot Multiple Lines in Matplotlib
How to Plot Histogram from List of Data in Python

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories