Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to plot ellipse given a general equation in R?

Tags:

math

plot

r

ellipse

Ellipse general equation:

a * x ^ 2 + b * y ^ 2 + c * x * y + d * x + e * y + f = 0

enter image description here

like image 456
Manjunath Avatar asked Jan 24 '17 05:01

Manjunath


People also ask

How do you graph the general form of an ellipse?

The center, orientation, major radius, and minor radius are apparent if the equation of an ellipse is given in standard form: (x−h)2a2+(y−k)2b2=1. To graph an ellipse, mark points a units left and right from the center and points b units up and down from the center. Draw an ellipse through these points.

What is the general equation of an ellipse conic section?

The standard form of equation of a conic section is Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, where A, B, C, D, E, F are real numbers and A ≠ 0, B ≠ 0, C ≠ 0. If B^2 – 4AC < 0, then the conic section is an ellipse.


Video Answer


1 Answers

The other answer shows you how to plot the ellipse, when you know both its centre and major axes. But they are not evident from the general ellipse equation. So here, I will start from scratch.

Omitting mathematical derivation, you need to solve for the centre from the following equation:

enter image description here

enter image description here

(oops: should be "generate v" not "generate u"; I can't fix it as the original LaTeX is now missing and I don't want to type again...)

Here is an R function to do this:

plot.ellipse <- function (a, b, c, d, e, f, n.points = 1000) {
  ## solve for centre
  A <- matrix(c(a, c / 2, c / 2, b), 2L)
  B <- c(-d / 2, -e / 2)
  mu <- solve(A, B)
  ## generate points on circle
  r <- sqrt(a * mu[1] ^ 2 + b * mu[2] ^ 2 + c * mu[1] * mu[2] - f)
  theta <- seq(0, 2 * pi, length = n.points)
  v <- rbind(r * cos(theta), r * sin(theta))
  ## transform for points on ellipse
  z <- backsolve(chol(A), v) + mu
  ## plot points
  plot(t(z), type = "l")
  }

Several remarks:

  1. There are conditions for parameters a, b, ..., f in order to ensure that the equation is an ellipse rather than something else (say parabolic). So, do not pass in arbitrary parameter values to test. In fact, from the equation you can roughly see such requirement. For example, matrix A must be positive-definite, so a > 0 and det(A) > 0; also, r ^ 2 > 0.
  2. I have used Cholesky factorization, as this is my favourite. However, the most beautiful result comes from Eigen decomposition. I will not pursue further on this part. If you are interested in it, read my another answer Obtain vertices of the ellipse on an ellipse covariance plot (created by car::ellipse). There are beautiful figures to illustrate the geometry of Cholesky factorization and Eigen decomposition.
like image 141
Zheyuan Li Avatar answered Sep 16 '22 22:09

Zheyuan Li