【发布时间】:2018-12-05 07:45:28
【问题描述】:
我有来自两组的xy 数据,其中每个点也有对应的xend 和yend 坐标,它们指示从该点开始的箭头在哪里结束:
set.seed(1)
df <- data.frame(x=c(rnorm(50,-1,0.5),rnorm(50,1,0.5)),y=c(rnorm(50,-1,0.5),rnorm(50,1,0.5)),group=c(rep("A",50),rep("B",50)))
df$arrow.x.end <- c(df$x[1:50]+runif(50,0,0.25),df$x[51:100]-runif(50,0,0.25))
df$arrow.y.end <- c(df$y[1:50]+runif(50,0,0.25),df$y[51:100]-runif(50,0,0.25))
A组的箭头一般指向B组,反之亦然:
library(ggplot2)
ggplot(df,aes(x=x,y=y,color=group))+geom_point()+theme_minimal()+
geom_segment(aes(x=x,y=y,xend=arrow.x.end,yend=arrow.y.end),arrow=arrow())+
theme(legend.position="none")
我正在寻找一种仅用两个箭头绘制点的方法,每组一个。 箭头将从每组的质心开始,将有一个斜率,即每组的中间斜率。理想情况下,箭头也将具有作为多边形的每组的中值斜率的标准误差。
这是我目前所做的:
library(dplyr)
slope.df <- df %>%
dplyr::group_by(group) %>%
dplyr::mutate(slope=(arrow.y.end-y)/abs((arrow.x.end-x)),length=sqrt((arrow.y.end-y)^2+(arrow.x.end-x)^2)) %>%
dplyr::summarise(slope.median=mean(slope),
slope.median.se=1.2533*(sd(slope)/sqrt(n())),
median.length=median(length),
x.start=median(x),y.start=median(y)) %>%
dplyr::mutate(x.end=x.start+sign(slope.median)*(median.length/sqrt(2))) %>%
dplyr::mutate(y.end=sign(slope.median)*((x.end-x.start)*slope.median))
计算每个箭头的斜率及其长度。然后每组的中值斜率、中值斜率的标准误差和中值长度。现在我将中间箭头的xend 和yend 计算为:
median.length^2 <- xend^2 + xend^2
但我用了别的东西。
所以绘制这个:
ggplot(df,aes(x=x,y=y,color=group))+geom_point()+theme_minimal()+theme(legend.position="none")+
geom_segment(aes(x=x.start,y=y.start,xend=x.end,yend=y.end),arrow=arrow(),data=slope.df)
如果有更好的方法以及如何添加标准错误多边形,有什么建议吗?
【问题讨论】: