Ellipse representing horizontal and vertical error bars with R
-
25-01-2021 - |
문제
In R, how to use ellipses to represent error bars (standard deviation) for x and y variables if only summary data, i.e. mean and SD for different data sets, are available. Any feedback is appreciated.
해결책
You can write your own function like this one:
draw_ellipse = function (mean_x, mean_y, sd_x, sd_y)
{
ellipse <- function (x) { sin(acos(x)) }
t = seq(-1, 1, length.out = 100)
el_y = sd_y*ellipse(t)
newx = mean_x + sd_x * t
polygon(c(newx, rev(newx)), c(mean_y + el_y, rev(mean_y - el_y)), col = "grey", border = NA)
}
You can use it very easily using apply()
:
x = runif(10)
y = runif(10)
sd_x = abs(rnorm(10, 0.1, 0.02))
sd_y = abs(rnorm(10, 0.05, 0.01))
plot(x, y)
df = data.frame(x, y, sd_x, sd_y)
apply(df, 1, function (x) { draw_ellipse(x[1], x[2], x[3], x[4]) })
points(x, y, pch = 3)
Solution for plotting ellipses with different colors:
draw_ellipse = function (mean_x, mean_y, sd_x, sd_y, colidx)
{
ellipse <- function (x) { sin(acos(x)) }
t = seq(-1, 1, length.out = 100)
el_y = sd_y*ellipse(t)
newx = mean_x + sd_x * t
polygon(c(newx, rev(newx)), c(mean_y + el_y, rev(mean_y - el_y)), col = as.character(colors[colidx]), border = NA)
}
x = runif(10)
y = runif(10)
sd_x = abs(rnorm(10, 0.1, 0.02))
sd_y = abs(rnorm(10, 0.05, 0.01))
plot(x, y)
colors = rainbow(length(x))
df = data.frame(x, y, sd_x, sd_y, colidx = 1:length(x))
apply(df, 1, function (x) { draw_ellipse(x[1], x[2], x[3], x["sd_y"], x["colidx"]) })
points(x, y, pch = 3)
다른 팁
You might like the function car::ellipse
, i.e., the ellipse() function in the car package.
The ellipse
function in the ellipse
package will take summary information (including correlation) and provide the ellipse representing the confidence region.
제휴하지 않습니다 StackOverflow