如何使用ggplot绘制多个ecdf?

Leg*_*end 4 statistics r ggplot2

我有一些格式如下的数据:

    2     2
    2     1
    2     1
    2     1
    2     1
    2     1
    2     2
    2     1
    2     1
    2     1
    2     2
    2     2
    2     1
    2     1
    2     2
    2     2
    2     1
    2     1
    2     1
    2     1
    2     1
    2     1
    2     1
    3     1
    3     1
    3     1
    3     3
    3     2
    3     2
    4     4
    4     2
    4     4
    4     2
    4     4
    4     2
    4     2
    4     4
    4     2
    4     2
    4     1
    4     1
    4     2
    4     3
    4     1
    4     3
    6     1
    6     1
    6     2
    7     1
    7     1
    7     1
    7     1
    7     1
    8     2
    8     2
    8     2
    8     2
    8     2
    8     2
   12     1
   12     1
   12     1
   12     1
   12     1
Run Code Online (Sandbox Code Playgroud)

我正在尝试为ecdf第一列中的每个不同值绘制此数据集.因此,在这种情况下,我想在图表上绘制7条ecdf曲线(一条用于第一列中有2条的所有点,一条用于第一列中有3条的所有点,依此类推......).对于一列,我可以使用以下内容绘制ecdf:

data = read.table("./test", header=F)
data1 = data[data$V1 == 2,]
qplot(unique(data1$V2), ecdf(data1$V2)(unique(data1$V2)), geom='step')
Run Code Online (Sandbox Code Playgroud)

但我无法理解如何绘制多条曲线.有什么建议?

Ari*_*man 13

如果你离开qplot()会更容易:

library(plyr)
library(ggplot2)
d.f <- data.frame(
  grp = as.factor( rep( c("A","B"), each=40 ) ) ,
  val = c( sample(c(2:4,6:8,12),40,replace=TRUE), sample(1:4,40,replace=TRUE) )
  )
d.f <- arrange(d.f,grp,val)
d.f.ecdf <- ddply(d.f, .(grp), transform, ecdf=ecdf(val)(val) )

p <- ggplot( d.f.ecdf, aes(val, ecdf, colour = grp) )
p + geom_step()
Run Code Online (Sandbox Code Playgroud)

您还可以轻松添加facet_wrap多个组和xlab/或ylab标签.

多个ecdfs

d.f <- data.frame(
  grp = as.factor( rep( c("A","B"), each=120 ) ) ,
  grp2 = as.factor( rep( c("cat","dog","elephant"), 40 ) ) ,
  val = c( sample(c(2:4,6:8,12),120,replace=TRUE), sample(1:4,120,replace=TRUE) )
  )
d.f <- arrange(d.f,grp,grp2,val)
d.f.ecdf <- ddply(d.f, .(grp,grp2), transform, ecdf=ecdf(val)(val) )

p <- ggplot( d.f.ecdf, aes(val, ecdf, colour = grp) )
p + geom_step() + facet_wrap( ~grp2 )
Run Code Online (Sandbox Code Playgroud)

使用2个分组变量


小智 6

自2012年底以来,ggplot2包含一个用于打印ecdfs的专用函数:ggplot2 docs.

那里的例子甚至比Ari的好解更短:

df <- data.frame(x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)),
             g = gl(2, 100))
ggplot(df, aes(x, colour = g)) + stat_ecdf()
Run Code Online (Sandbox Code Playgroud)

ECDF