【发布时间】:2011-11-22 15:17:22
【问题描述】:
在 R 中,如果只有汇总数据(即不同数据集的平均值和 SD)可用,如何使用椭圆来表示 x 和 y 变量的误差线(标准差)。任何反馈表示赞赏。
【问题讨论】:
标签: r plot drawellipse
在 R 中,如果只有汇总数据(即不同数据集的平均值和 SD)可用,如何使用椭圆来表示 x 和 y 变量的误差线(标准差)。任何反馈表示赞赏。
【问题讨论】:
标签: r plot drawellipse
您可以像这样编写自己的函数:
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)
}
您可以使用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)
绘制不同颜色椭圆的解决方案:
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)
【讨论】:
border = NA,它将打印每个椭圆的边框,或者尝试更改 col 参数以沿某些调色板进行更改(请参阅?palette)。然后,您需要将额外的参数 col 添加到 draw_ellipse 函数并在 apply 调用中提供它。
df = data.frame(x, y, sd_x, sd_y, col = 1:length(x)),然后在 apply 调用中使用它。请参阅我的更新答案。
您可能喜欢函数 car::ellipse ,即 car 包中的 ellipse() 函数。
【讨论】:
ellipse 包中的ellipse 函数将获取摘要信息(包括相关性)并提供表示置信区域的椭圆。
【讨论】: