'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?
Solution 1:[1]
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.
Solution 2:[2]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | VladimĂr Kunc |
Solution 2 | Tom |