<p>参考文章<a href="http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/" rel="noreferrer">How to draw a covariance error ellipse</a>。</p>
<p>以下是python实现:</p>
<pre><code>import numpy as np
from scipy.stats import norm, chi2
def cov_ellipse(cov, q=None, nsig=None, **kwargs):
"""
Parameters
----------
cov : (2, 2) array
Covariance matrix.
q : float, optional
Confidence level, should be in (0, 1)
nsig : int, optional
Confidence level in unit of standard deviations.
E.g. 1 stands for 68.3% and 2 stands for 95.4%.
Returns
-------
width, height, rotation :
The lengths of two axises and the rotation angle in degree
for the ellipse.
"""
if q is not None:
q = np.asarray(q)
elif nsig is not None:
q = 2 * norm.cdf(nsig) - 1
else:
raise ValueError('One of `q` and `nsig` should be specified.')
r2 = chi2.ppf(q, 2)
val, vec = np.linalg.eigh(cov)
width, height = 2 * sqrt(val[:, None] * r2)
rotation = np.degrees(arctan2(*vec[::-1, 0]))
return width, height, rotation
</code></pre>
<p>在Joe Kington的回答中,<em>标准差</em>的含义是<strong>错误的</strong>。
通常我们使用1,2西格玛来表示68%,95%的置信水平,但他回答的2西格玛椭圆不包含95%的总分布概率。正确的方法是使用卡方分布来确定椭圆大小,如<a href="http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/" rel="noreferrer">post</a>所示。</p>