有一些关于在ggplot中绘制累积密度的帖子.我目前正在使用Easier方式接受的答案来绘制ggplot中的累积频率分布?用于绘制我的累积计数.但是这种解决方案涉及预先预先计算这些值.
在这里,我正在寻找一个纯粹的ggplot解决方案.让我们展示一下到目前为止:
x <- data.frame(A=replicate(200,sample(c("a","b","c"),1)),X=rnorm(200))
Run Code Online (Sandbox Code Playgroud)
stat_ecdf我可以使用ggplot stat_ecdf,但它只绘制累积密度:
ggplot(x,aes(x=X,color=A)) + geom_step(aes(y=..y..),stat="ecdf")
Run Code Online (Sandbox Code Playgroud)

我想做类似以下的事情,但它不起作用:
ggplot(x,aes(x=X,color=A)) + geom_step(aes(y=..y.. * ..count..),stat="ecdf")
Run Code Online (Sandbox Code Playgroud)
cumsum 和 stat_bin我发现了一个使用cumsum和的想法stat_bin:
ggplot(x,aes(x=X,color=A)) + stat_bin(aes(y=cumsum(..count..)),geom="step")
Run Code Online (Sandbox Code Playgroud)

但正如您所看到的,下一种颜色不是从y=0最后一种颜色开始,而是最后一种颜色结束的颜色.
从最好到最差我想拥有什么:
理想情况下,一个简单的解决方案是不工作
ggplot(x,aes(x=X,color=A)) + geom_step(aes(y=..y.. * ..count..),stat="ecdf")
Run Code Online (Sandbox Code Playgroud)一种更复杂的stat_ecdf计数方法.
cumsum方法,因为它会产生更糟糕的(分类)结果.Did*_*rts 21
这不会直接解决线路分组问题,但它会解决方法.
您可以stat_bin()根据A级别向数据子集的位置添加三个调用.
ggplot(x,aes(x=X,color=A)) +
stat_bin(data=subset(x,A=="a"),aes(y=cumsum(..count..)),geom="step")+
stat_bin(data=subset(x,A=="b"),aes(y=cumsum(..count..)),geom="step")+
stat_bin(data=subset(x,A=="c"),aes(y=cumsum(..count..)),geom="step")
Run Code Online (Sandbox Code Playgroud)

另一种可能性是将..y..每个级别的值与观察次数相乘.为了在此时获得此数量的观察,我发现的方法是在绘制之前预先计算它们并将它们添加到原始数据帧.我把这个专栏命名为len.然后在geom_step()内部,aes()您应该定义您将使用变量len=len,然后将y值定义为y=..y.. * len.
set.seed(123)
x <- data.frame(A=replicate(200,sample(c("a","b","c"),1)),X=rnorm(200))
library(plyr)
df <- ddply(x,.(A),transform,len=length(X))
ggplot(df,aes(x=X,color=A)) + geom_step(aes(len=len,y=..y.. * len),stat="ecdf")
Run Code Online (Sandbox Code Playgroud)

小智 8
您可以row_number对组进行应用,并将其用作 ageom_step或其他几何图形中的 Y 美学。您只需要按 排序X,否则值将像它们在数据框中一样无序显示。
ggplot(x %>%
group_by(A) %>%
arrange(X) %>%
mutate(rn = row_number())) +
geom_step(aes(x=X, y=rn, color=A))
Run Code Online (Sandbox Code Playgroud)