how to plot ellipse given a general equation in R?

前端 未结 3 1714
南笙
南笙 2020-12-16 06:14

Ellipse general equation:

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

3条回答
  •  甜味超标
    2020-12-16 07:09

    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:

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

提交回复
热议问题