Creating a Confidence Ellipses in a sccatterplot using matplotlib

前端 未结 2 996
面向向阳花
面向向阳花 2020-12-04 11:32

How to creating a Confidence Ellipses in a sccatterplot using matplotlib?

The following code works until creating scatter plot. Then, does anyone familiar with putti

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 12:24

    After giving the accepted answer a go, I found that it doesn't choose the quadrant correctly when calculating theta, as it relies on np.arccos:

    oops

    Taking a look at the 'possible duplicate' and Joe Kington's solution on github, I watered his code down to this:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
    
    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]
    
    x = [5,7,11,15,16,17,18]
    y = [25, 18, 17, 9, 8, 5, 8]
    
    nstd = 2
    ax = plt.subplot(111)
    
    cov = np.cov(x, y)
    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    w, h = 2 * nstd * np.sqrt(vals)
    ell = Ellipse(xy=(np.mean(x), np.mean(y)),
                  width=w, height=h,
                  angle=theta, color='black')
    ell.set_facecolor('none')
    ax.add_artist(ell)
    plt.scatter(x, y)
    plt.show()
    

    neg slope

提交回复
热议问题