def pca_ellipse(data, loc=None, ax=None, **ellipse_kwargs):
  '''Finds the 2d PCA ellipse of given data and plots it.
  loc: center of the ellipse [default: mean of the data]
  '''
  from sklearn.decomposition import PCA  # Late import; sklearn is optional
  pca = PCA(n_components=2).fit(data)
  if loc is None:
    loc = pca.mean_
  if ax is None:
    ax = plt.gca()
  cov = pca.explained_variance_ * pca.components_.T
  u,s,v = np.linalg.svd(cov)
  width,height = 2*np.sqrt(s[:2])
  angle = np.rad2deg(np.arctan2(u[1,0], u[0,0]))
  ell = Ellipse(xy=loc, width=width, height=height, angle=angle,
                **ellipse_kwargs)
  ax.add_patch(ell)
  return ell
Finds the 2d PCA ellipse of given data and plots it.
  loc: center of the ellipse [default: mean of the data]