# Matplotlib 密度图

Suraj Joshi 2024年2月15日

## 使用 `scipy.stats` 模块中的 `gaussian_kde()` 方法生成密度图

``````import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kde

data = [2, 3, 3, 4, 2, 1, 5, 6, 4, 3, 3, 3, 6, 4, 5, 4, 3, 2]
density = kde.gaussian_kde(data)
x = np.linspace(-2, 10, 300)
y = density(x)

plt.plot(x, y)
plt.title("Density Plot of the data")
plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kde

data = [2, 3, 3, 4, 2, 1, 5, 6, 4, 3, 3, 3, 6, 4, 5, 4, 3, 2]
prob_density = kde.gaussian_kde(data)
prob_density.covariance_factor = lambda: 0.25
prob_density._compute_covariance()

x = np.linspace(-2, 10, 300)
y = prob_density(x)

plt.plot(x, y)
plt.title("Density Plot of the data")
plt.show()
``````

## 使用 `seaborn` 包中的 `kdeplot()` 方法生成密度图

``````import matplotlib.pyplot as plt
import seaborn as sns

data = [2, 3, 3, 4, 2, 1, 5, 6, 4, 3, 3, 3, 6, 4, 5, 4, 3, 2]
sns.kdeplot(data, bw=0.25)
plt.show()
``````

## 使用 `distplot()` 方法从 `seaborn` 包中生成密度图

``````import matplotlib.pyplot as plt
import seaborn as sns

data = [2, 3, 3, 4, 2, 1, 5, 6, 4, 3, 3, 3, 6, 4, 5, 4, 3, 2]
sns.distplot(data, hist=False)
plt.show()
``````

## 在 `pandas.DataFrame.plot()` 方法中设置 `kind='density'`来生成密度图

``````import pandas as pd
import matplotlib.pyplot as plt

data = [2, 3, 3, 4, 2, 1, 5, 6, 4, 3, 3, 3, 6, 4, 5, 4, 3, 2]
df = pd.DataFrame(data)
df.plot(kind="density")
plt.show()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.