python - 使用 matplotlib 和 seaborn 生成并绘制高斯混合图

标签 python matplotlib graph seaborn

我正在尝试生成下面的图。具体来说,混合标签非常好地显示这是高斯的混合。

enter image description here

我用下面的代码得到了第二张图片,如果有人可以帮助我知道如何标准化两个组成法线(所以它们低于混合物),那就太好了:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

n = 10000
mu = [0, 10]
sigma = [1, 1]
samples = []
samples0 = []
samples1 = []
for i in range(n):  # iteratively draw samples
    Z = np.random.choice([0, 1])  # latent variable
    if Z == 0:
        samples0.append(np.random.normal(mu[Z], sigma[Z], 1))
    else:
        samples1.append(np.random.normal(mu[Z], sigma[Z], 1))

    samples.append(np.random.normal(mu[Z], sigma[Z], 1))
sns.distplot(samples, hist=False, kde_kws={"shade": False})
sns.distplot(samples0, hist=False, kde_kws={"shade": True})
sns.distplot(samples1, hist=False, kde_kws={"shade": True})
plt.show()

t

最佳答案

据我所知,如果你想使用seaborn.distplot,你只能通过添加图像范围之外的点来实现这一点。然而,您可以使用 scipy 和 matplotlib 轻松复制 seaborn 行为。请注意,分布并不完全填充相同的空间,这可能是核密度估计的产物。您可以手动调整带宽来解决此问题。

或者,如果您已经知道分布的参数,则可以只绘制函数值而不是核密度估计,这似乎是在上图中完成的。

import numpy as np
import scipy.stats
import matplotlib.pyplot as plt

n = 10000
mu = [0, 10]
sigma = [1, 1]
samples = []
samples0 = []
samples1 = []
for i in range(n):  # iteratively draw samples
    Z = np.random.choice([0, 1])  # latent variable
    if Z == 0:
        samples0.append(np.random.normal(mu[Z], sigma[Z]))
        samples.append(samples0[-1])
    else:
        samples1.append(np.random.normal(mu[Z], sigma[Z]))
        samples.append(samples1[-1])

grid = np.linspace(min(samples)-0.5, max(samples)+0.5,1000)
y = scipy.stats.gaussian_kde(samples).evaluate(grid)
# Double the number of points to make sure the bandwidth in the KDE will be the same
y0 = scipy.stats.gaussian_kde(samples0*2).evaluate(grid)
y1 = scipy.stats.gaussian_kde(samples1*2).evaluate(grid)
# Multiply by maximum height to scale
y /= max(y)
y0 /= max(y0)
y1 /= max(y1)
plt.plot(grid, y0, label='Component 1')
plt.fill_between(grid, 0, y0, alpha=0.5)
plt.plot(grid, y1, label='Component 2')
plt.fill_between(grid, 0, y1, alpha=0.5)
plt.plot(grid, y, '--', label='Mixture')
plt.legend()
plt.show()

关于python - 使用 matplotlib 和 seaborn 生成并绘制高斯混合图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59281038/

相关文章:

python - 使用 Matplotlib 和 mpld3 在 Web 浏览器上生成多个图形

python - Xaxis 标签与数据点不匹配 - Pandas/Matplotlib

java - 帮助 :Graph contest problem: maybe a modified Dijkstra or another alternative algorithm

javascript - 如何创建移动图表折线图js的背景?

algorithm - 计算 DAG 中每个顶点的单源最短路径算法背后的直觉

python - 如何创建遍历列表所有对角线可能性的 for 循环?

python - Pandas:写入原始数据框。设置复制警告

python - Python用渐变绘制一条线,其中一种颜色是透明的

Python:根据单词的第一个字符拆分列表

python - 无法从整数创建 PyObject