OpenJNY
3/11/2018 - 6:36 PM

2次元ガウス分布の2種類のプロット方法．ひとつは contourf を使うもので，もうひとつは pathes.Ellipse で std=1,2 信頼楕円を描写する

2次元ガウス分布の2種類のプロット方法．ひとつは contourf を使うもので，もうひとつは pathes.Ellipse で std=1,2 信頼楕円を描写する

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

# Parameters
mu = [0,0]
Sigma = [[1.5, .5],[.5, 1]]

fig, axes = plt.subplots(1,2, figsize=(10,5))

# 1. contourf
# -----------
x_min, x_max = (-3, 3)
y_min, y_max = (-3, 3)
h = .05
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
zz = np.c_[xx.ravel(), yy.ravel()]
Z = multivariate_normal(mu, Sigma).pdf(zz)
Z = Z.reshape(xx.shape)
axes[0].contourf(xx, yy, Z, cmap=plt.cm.bone)
axes[0].set_title('contourf')

# 2. patches.Ellipse
# ------------------
def get_ellipse(mean, cov, std=1):
eigvalues, V = np.linalg.eigh(cov)
order = eigvalues.argsort()[::-1]
eigvalues, V = eigvalues[order], V[:,order]
w = 2 * eigvalues[0] * std
h = 2 * eigvalues[1] * std
vec = V[:,0]
if vec[0] < 0:
vec = vec * [-1, 1]
deg = np.degrees(np.arccos(vec.dot([1,0])))
return w, h, deg

w, h, deg = get_ellipse(mu, Sigma)
fc = plt.cm.Set1(0)
ec = plt.cm.Set1(0)
e_std1 = patches.Ellipse(xy=mu, width=w, height=h, angle=deg,
fc=fc, ec=ec, lw=3, fill=False)
e_std2 = patches.Ellipse(xy=mu, width=2*w, height=2*h, angle=deg,
fc=fc, ec=ec, lw=3, fill=False)