与ggplot2的边界

时间:2015-12-17 23:17:02

标签: r ggplot2

我使用ggplot2制作了以下图表。如你所见,我有3种不同的颜色为红黑蓝。我想在两个边界上绘制两条曲线,将红点与黑点分开,蓝点与黑点分开。我完全失去了任何想法。

我的代码是:

datax=data.frame(x=y_data,y=x_data,
                 Diff_Motif_XY=factor(diff_motif,levels=c(1,0,‌​-1)),
                 size=factor(abs(diff_motif))) 
#
p=ggplot(datax,aes(x,y))+ 
     geom_point(aes(colour = Diff_Motif_XY,size=size))+ 
     xlab(cond2)+ 
     ylab(cond1)+ 
     scale_colour_manual(values=c("red","black","blue"))

Please click for the image

1 个答案:

答案 0 :(得分:1)

我(也太)好奇。我认为看起来边界是一个双曲线。可以使用类似optim之类的东西来计算最佳边界双曲线,但它可能是相当多的工作而且可能不会收敛。

# Generate some data because the OP did not provide any

npts <- 30000
l_data <- pmax(0,runif(npts,-10,20))
s_data <- (20-l_data + 10)/6
xstar <- -5.1
ystar <- -5.1
x_data <- pmax(0,l_data + rnorm(npts,0,s_data)) + xstar
y_data <- pmax(0,l_data + rnorm(npts,0,s_data)) + ystar
ha <- 6.0
hb <- 6.0

xy2 <- ((x_data-xstar)/ha)^2 - ((y_data-ystar)/hb)^2 + 0.8*rnorm(npts)


diff_motif <- ifelse(xy2>1,1,ifelse(-xy2<1,0,-1))
cond1 <- ""
cond2 <- ""


# We need this to plot our hyperbola
genhyperbola <- function( cx,cy,a,b,u0,u1,nu,swap=F)
{
  # Generate a hyperbola through the parametric representation
  #  which uses sinh and cosh 
  #  We generate nu segements from u0 to u1
  #  swap just swaps the x and y axes allowing for a north-south hyperbola (swap=T)
  #
  #  https://en.wikipedia.org/wiki/Hyperbola
  #
  u <- seq(u0,u1,length.out=nu)
  x <- a*cosh(u)
  y <- b*sinh(u)
  df <- data.frame(x=x,y=y)
  df$x <- df$x + cx
  df$y <- df$y + cy
  if (swap){
    # for north-south hyperbolas
    tmp <- df$x
    df$x <- df$y
    df$y <- tmp
  }
  return(df)
}
hyp1 <- genhyperbola(xstar,ystar, ha,hb, 0,2.2,100, swap=F)
hyp2 <- genhyperbola(xstar,ystar, ha,hb, 0,2.2,100, swap=T)

datax=data.frame(x=x_data,y=y_data,
                 Diff_Motif_XY=factor(diff_motif,levels=c(1,0,-1)),
                 size=0) 

eqlab1 <- sprintf("((x+%.1f)/%.1f)^{2}-((y+%.1f)/%.1f)^{2} == 1",xstar,ha,ystar,hb)
eqlab2 <- sprintf("((y+%.1f)/%.1f)^{2}-((x+%.1f)/%.1f)^{2} == 1",ystar,hb,xstar,ha)
#
p=ggplot(datax,aes(x,y))+ 
  geom_point(aes(colour = Diff_Motif_XY),shape=".")+ 
  geom_path(data=hyp1,aes(x,y),color=I("purple"),size=1)+
  geom_path(data=hyp2,aes(x,y),color=I("brown"),size=1)+
  xlab(cond2)+ 
  ylab(cond1)+ 
  scale_colour_manual(values=c("blue","black","red")) +
  annotate('text', x=xstar+20, y=ystar+2,  
           label = eqlab1,parse = TRUE,size=6,color="purple") +
  annotate('text', x=xstar+5,  y=ystar+20, 
           label = eqlab2,parse = TRUE,size=6,color="brown") 

print(p)

这是图像:

enter image description here