简体   繁体   中英

Contour plots for multivariate gaussian

I'm trying to use a contour plot to visualize a multivariate normal distribution.

import numpy as np
from scipy.stats import multivariate_normal

mean = (0, 0)
cov = [[1, 0.75], 
       [0.75, 1]]
data = np.random.multivariate_normal(mean, cov,size=1000)
var = multivariate_normal(mean=mean, cov=cov)
z = var.pdf(data)
plt.contour(data,z)

>>>
ValueError: Contour levels must be increasing

My goal is simply a contour plot of the multivariate distribution, much like a 2D histogram. However, I seem to be misunderstanding the function's intent.

Is there a better way to accomplish this effect?

A solution using the same libraries you were using:

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

x, y = np.mgrid[-10:10:.1, -10:10:.1]
rv = multivariate_normal([0, 0], [[10.0, 2.], [2., 10.0]])
data = np.dstack((x, y))
z = rv.pdf(data)
plt.contourf(x, y, z, cmap='coolwarm')
plt.show()

You can use seaborn kde plot:

import seaborn as sns
sns.kdeplot(data, bw=.15)
plt.show()

as described here https://seaborn.pydata.org/generated/seaborn.kdeplot.html for easy plotting.

I know it is not the exact answer to your problem but it might be sufficient answer for you if you are willing to install the seaborn library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM