I have some data formatted like the following:
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
I am trying to plot the ecdf
of this dataset for each distinct value in the first column. Therefore in this case, I want to plot 7 ecdf curves on a graph (one for all points that have 2 in their first column, one for all points that have 3 in their first column and so on...). For one column, I am able to plot the ecdf using the following:
data = read.table("./test", header=F)
data1 = data[data$V1 == 2,]
qplot(unique(data1$V2), ecdf(data1$V2)(unique(data1$V2)), geom='step')
But I am not able to understand how to plot multiple curves. Any suggestions?
Easier if you move away from 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()
You can also easily add in facet_wrap
for more than one group, and xlab
/ylab
for labels.
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 )
Since the end of 2012, ggplot2 includes a dedicated function for printing ecdfs: ggplot2 docs.
The example from there is even shorter than the good solution by 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()
精彩评论