21

我有一个 R 函数,它为散点图生成 95% 的置信椭圆。输出如下所示,每个椭圆(50 行)默认为 50 个点:

           [,1]         [,2]
 [1,]  0.097733810  0.044957994
 [2,]  0.084433494  0.050337990
 [3,]  0.069746783  0.054891438

我想在ggplot2散点图上为一个称为“站点”的因子的每个级别叠加多个这样的椭圆,由该命令生成:

> plat1 <- ggplot(mapping=aes(shape=site, size=geom), shape=factor(site)); plat1 + geom_point(aes(x=PC1.1,y=PC2.1))

这是在一个数据集上运行的,dflat它看起来像这样:

site      geom         PC1.1        PC2.1       PC3.1        PC1.2       PC2.2
1 Buhlen 1259.5649 -0.0387975838 -0.022889782  0.01355317  0.008705276  0.02441577
2 Buhlen  653.6607 -0.0009398704 -0.013076251  0.02898955 -0.001345149  0.03133990

结果很好,但是当我尝试添加椭圆时(假设这个站点,称为“Buhlen”):

> plat1 + geom_point(aes(x=PC1.1,y=PC2.1)) + geom_path(data=subset(dflat, site="Buhlen"),mapping=aes(x=ELLI(PC1.1,PC2.1)[,1],y=ELLI(PC1.1,PC2.1)[,2]))

我收到一条错误消息:"Error in data.frame(x = c(0.0977338099339815, 0.0844334944904515, 0.0697467834016782, : arguments imply differing number of rows: 50, 211

我过去设法解决了这个问题,但我不记得如何解决了。似乎 geom_path 依赖于相同的点而不是绘制新的点。任何帮助,将不胜感激。

4

2 回答 2

23

也许这可以帮助你:

#bootstrap
set.seed(101)
n <- 1000
x <- rnorm(n, mean=2)
y <- 1.5 + 0.4*x + rnorm(n)
df <- data.frame(x=x, y=y, group="A")
x <- rnorm(n, mean=2)
y <- 1.5*x + 0.4 + rnorm(n)
df <- rbind(df, data.frame(x=x, y=y, group="B"))

#calculating ellipses
library(ellipse)
df_ell <- data.frame()
for(g in levels(df$group)){
df_ell <- rbind(df_ell, cbind(as.data.frame(with(df[df$group==g,], ellipse(cor(x, y), 
                                         scale=c(sd(x),sd(y)), 
                                         centre=c(mean(x),mean(y))))),group=g))
}
#drawing
library(ggplot2)
p <- ggplot(data=df, aes(x=x, y=y,colour=group)) + geom_point(size=1.5, alpha=.6) +
  geom_path(data=df_ell, aes(x=x, y=y,colour=group), size=1, linetype=2)

输出如下所示:

在此处输入图像描述

是更复杂的示例。

于 2011-03-10T15:50:08.343 回答
22

Keelan Evanini、Ingrid Rosenfelder 和 Josef Fruehwald (JoFrhwld@gmail.com) 创建了 95% 置信区间椭圆的 ggplot2 stat 实现(以及在 ggplot2 中绘制椭圆的更简单方法):

GitHub stat-ellipse.R

他们的网站

您可以将其用作:

library(ggplot2)
library(devtools)
library(digest)
source_url("https://raw.github.com/low-decarie/FAAV/master/r/stat-ellipse.R")    
qplot(data=df, x=x, y=y, colour=colour)+stat_ellipse()

在此处输入图像描述

创建数据

set.seed(101)
n <- 1000
x <- rnorm(n, mean=2)
y <- 1.5 + 0.4*x + rnorm(n)
colour <- sample(c("first", "second"), size=n, replace=T)
df <- data.frame(x=x, y=y, colour=colour)
于 2012-04-17T11:45:22.027 回答