1

I am trying to draw uncertainty ellipse which is the ellipse of points that are one standard deviation away from the mean. I am using this code to do it: https://stackoverflow.com/a/25022642/7448860

But, instead of an ellipse it draws a line.

I'm plotting 2 random variable (x, y), so the size of covariance matric is 2 x 2. To compute covariance matric I'm using Kalman Filter Algorithm, so I don’t need to use np.cov().

Code:

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 = [0]
y = [0]
cov = [[0.25, 0.5 ], [0.5, 1.]]

nstd = 1
ax = plt.subplot(111)

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()

Output: enter image description here

How can I draw ellipse one standard deviation away from the mean?

I tried:

x = [0,1,0,1]
y = [0,0,1,1]

But, it plots: enter image description here

Beginner
  • 1,202
  • 2
  • 20
  • 29
  • What is the value of your `w` and `h` variables? It is possible that you are actually drawing an ellipse but you are just zoomed in so that the ellipse appears to be line. – Jonny Morrill Feb 05 '19 at 02:02
  • The value of w=2.23606797749979, h=0.0. I tried h=2, but then the line disappears and there's only a dot. – Beginner Feb 05 '19 at 02:14
  • OK, your problem appears to be twofold: 1. An ellipse with a height of zero is essentially a completely flat line segment. 2. The range/domain is chosen based upon your data points, which is only (0,0). If you add some more data points, I am guessing that this will fix your visualization problem. For example: `x = [0,1,0,1]` and `y = [0,0,1,1]` – Jonny Morrill Feb 05 '19 at 02:22
  • I tried those x, y values, but still it plots a line. I updated my question. – Beginner Feb 05 '19 at 02:44
  • 1
    I also noticed you are manually setting the co-variance vectors. Shouldn't you be calculating them from the data points: `cov = np.cov(x, y)` – Jonny Morrill Feb 05 '19 at 03:04
  • Actually, I'm solving question 1 (d) of CH 3 of Probabilistic Robotics by Sebastian Thrun, in which I need to use Kalman Filter Algorithm to compute the covariance matrix. In addition, I get `nan` values when I use `np.cov(x, y)`. – Beginner Feb 05 '19 at 04:01
  • In any case, all one can comment about here is that the `cov` which you hardcode is not useful, because it consists of linear dependent vectors. So whatever is used to create those in your real code is not doing its job correctly. – ImportanceOfBeingErnest Feb 05 '19 at 15:01

0 Answers0