【问题标题】:How do I plot multiple ecdfs using ggplot?如何使用 ggplot 绘制多个 ecdf?
【发布时间】:2011-07-27 05:54:42
【问题描述】:

我有一些数据格式如下:

    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

我正在尝试为第一列中的每个不同值绘制此数据集的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')

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

【问题讨论】:

  • 请发布一个可重现的示例。即使模拟你的数据,我也无法让你现有的尝试奏效。
  • 对不起!我在声明中有一个错字。更新了一组有效的语句。

标签: r statistics ggplot2


【解决方案1】:

如果你离开 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()

您还可以轻松地为多个组添加facet_wrap,并为标签添加xlab/ylab

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 )

【讨论】:

  • 太棒了!非常感谢您的帮助!
【解决方案2】:

从 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()

【讨论】:

  • 很好看。添加了图表。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 2018-05-09
  • 2022-08-21
相关资源
最近更新 更多