[R] Regression on Circle/Sphere: Correlation Coefficient?
Leonard Mada
|m@d@ @end|ng |rom um|t@ro
Tue Nov 24 23:59:58 CET 2026
Dear R Users,
I stumbled upon an interesting question. I fitted a set of points to a
circle or to a circle segment (or sphere cap) and I wondered if there is
something equivalent to a correlation coefficient?
I have a dilemma in constructing such a coefficient. A value of 0 means
no correlation and a value of 1 means perfect correlation. But I do not
know if a value of -1 is meaningful or how to interpret it.
The example below illustrates the method:
# Regression on Circle (2D)
lm.circle = function(x, y) {
xm = mean(x); ym = mean(y);
dx = x - xm; dy = y - ym;
n = length(x);
S2 = x^2 + y^2;
Sdx = sum(S2*dx);
Sdy = sum(S2*dy);
#
divx = 2*(sum(x*dx) * sum(dy*y) - sum(x*dy) * sum(dx*y));
x0 = (Sdx * sum(dy*y) - Sdy * sum(dx*y)) / divx;
#
y0 = - (Sdx * sum(dy*x) - Sdy * sum(dx*x)) / divx;
# Radius:
r = sum((x-x0)^2, (y-y0)^2);
r = sqrt(r/n);
#
fit = list(C = c(x0, y0), R = r);
return(fit);
}
### Plot Circle:
lines.circle = function(r, centre = c(0,0), ..., n = 33) {
phi = seq(0, 2*pi, length.out = n);
phi[n] = phi[1];
x = r*sin(phi) + centre[1];
y = r*cos(phi) + centre[2];
lines(x, y, ...);
invisible(cbind(x,y));
}
### Example:
n = 30;
r = 10;
x0 = 5; y0 = 2; # Center
# Random data:
phi = (2*pi)*runif(n, 0, 3/5);
dri = runif(n, -1,1) / 10 * r;
x = x0 + (r+dri) * sin(phi);
y = y0 + (r+dri) * cos(phi);
# Fit
fit = lm.circle(x, y);
Cxy = fit$C;
phi.fit = atan2(x - Cxy[1], y - Cxy[2]);
# Predicted:
xPred = fit$R * sin(phi.fit) + Cxy[1];
yPred = fit$R * cos(phi.fit) + Cxy[2];
# Plot:
plot(x, y, xlim = range(x) + c(-1,1), ylim=range(y) + c(-1,1), asp=1)
lines.circle(fit$R, fit$C, col = "#C28092D2")
points(xPred, yPred, col = "red")
The code to fit a 3D sphere (which is generalizable) is on GitHub:
https://github.com/discoleo/R/blob/master/Stat/Regression.Circle.R
Various packages deal with cyclic data, but focus on testing uniformity
or performing regression once the angles are known (e.g. circular,
circularKDE, circda). I am unaware of any packages fitting spatial data
to a circle/sphere.
My primary interest was in a slightly different direction (fitting some
curved axis or cutting planes to 3D protein structures); but the
question above was interesting in itself.
Many thanks in advance for any hints.
Sincerely,
Leonard
More information about the R-help
mailing list