如何将两个累积频率图一起绘制

时间:2010-03-19 03:27:15

标签: r plot

我的数据如下:

#val  Freq1 Freq2
0.000 178 202
0.001 4611 5300
0.002 99 112
0.003 26 30
0.004 17 20
0.005 15 20
0.006 11 14
0.007 11 13
0.008 13 13
...many more lines..

可在此处找到完整数据: http://dpaste.com/173536/plain/

我打算做的是拥有累积图表 “val”为x轴,“Freq1”& “Freq2”为 y轴,在1个图中一起绘制。

我有这个代码。但它会创建两个图而不是1个。

dat <- read.table("stat.txt",header=F);
val<-dat$V1
freq1<-dat$V2
freq2<-dat$V3

valf1<-rep(val,freq1)
valf2<-rep(val,freq2)

valfreq1table<- table(valf1)
valfreq2table<- table(valf2)
cumfreq1=c(0,cumsum(valfreq1table))
cumfreq2=c(0,cumsum(valfreq2table))

plot(cumfreq1, ylab="CumFreq",xlab="Loglik Ratio")
lines(cumfreq1)
plot(cumfreq2, ylab="CumFreq",xlab="Loglik Ratio")
lines(cumfreq2)

采用这种方式的正确方法是什么?

3 个答案:

答案 0 :(得分:6)

data <- read.table("http://dpaste.com/173536/plain/", header = FALSE)

sample1 <- unlist(apply(as.matrix(data),1,function(x) rep(x[1],x[2])))
sample2 <- unlist(apply(as.matrix(data),1,function(x) rep(x[1],x[3])))

plot(ecdf(sample1), verticals=TRUE, do.p=FALSE,
main="ECDF plot for both samples", xlab="Scores", 
ylab="Cumulative Percent",lty="dashed")

lines(ecdf(sample2), verticals=TRUE, do.p=FALSE,
col.h="red", col.v="red",lty="dotted")

legend(100,.8,c("Sample 1","Sample 2"),
col=c("black","red"),lty=c("dashed","dotted"))

答案 1 :(得分:3)

尝试基础R中的ecdf()函数---如果内存服务则使用plot.stepfun() - 或者使用Frank Harrell在Hmisc中使用Ecdf()函数。以下是help(Ecdf)中使用分组变量在一个图中显示两个ecdf的示例:

 # Example showing how to draw multiple ECDFs from paired data
 pre.test <- rnorm(100,50,10)
 post.test <- rnorm(100,55,10)
 x <- c(pre.test, post.test)
 g <- c(rep('Pre',length(pre.test)),rep('Post',length(post.test)))
 Ecdf(x, group=g, xlab='Test Results', label.curves=list(keys=1:2))

答案 2 :(得分:1)

仅供记录,以下是“手动”在同一图中获得多行的方法:

plot(cumfreq1, ylab="CumFreq",xlab="Loglik Ratio", type="l") 
          # or type="b" for lines and points
lines(cumfreq2, col="red")