绘制ggplot2中的累积计数

时间:2013-08-22 12:05:15

标签: r ggplot2

有一些关于在ggplot中绘制累积密度的帖子。我目前正在使用Easier way to plot the cumulative frequency distribution in ggplot?中接受的答案来绘制我的累积计数。但是这个解决方案涉及事先预先计算这些值。

在这里,我正在寻找一个纯粹的ggplot解决方案。让我们展示一下到目前为止:

x <- data.frame(A=replicate(200,sample(c("a","b","c"),1)),X=rnorm(200))

ggplot的stat_ecdf

我可以使用ggplot的stat_ecdf,但它只绘制累积密度:

ggplot(x,aes(x=X,color=A)) + geom_step(aes(y=..y..),stat="ecdf")

enter image description here

我想做类似以下的事情,但它不起作用:

ggplot(x,aes(x=X,color=A)) + geom_step(aes(y=..y.. * ..count..),stat="ecdf")

cumsumstat_bin

我发现了使用cumsumstat_bin的想法:

ggplot(x,aes(x=X,color=A)) + stat_bin(aes(y=cumsum(..count..)),geom="step")

enter image description here

但正如您所看到的,下一种颜色不是从y=0开始,而是最后一种颜色的结束。

我要求的是

我希望从最好到最差的地方:

  1. 理想情况下,对无法正常工作的简单修复

    ggplot(x,aes(x=X,color=A)) + geom_step(aes(y=..y.. * ..count..),stat="ecdf")
    
  2. 使用stat_ecdf计算的更复杂方法。

  3. 最后的办法是使用cumsum方法,因为它会产生更糟糕的(分类)结果。

3 个答案:

答案 0 :(得分: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")

enter image description here

UPDATE - 使用geom_step()

的解决方案

另一种可能性是将..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") 

enter image description here

答案 1 :(得分:4)

您可以将row_number应用于各个组,并将其用作geom_step或其他几何图形中的Y美学。您只需要按X进行排序,否则值将像在数据框中一样无序显示。

ggplot(x %>% 
         group_by(A) %>% 
         arrange(X) %>% 
         mutate(rn = row_number())) + 
  geom_step(aes(x=X, y=rn, color=A))

Cumulative count by group

答案 2 :(得分:0)

似乎不需要len层内的参数ygeom_step(aes(len=len,y=..y.. * len),stat="ecdf")。并且len似乎不是geom_step中的参数。我们只需要使用

geom_step(aes(stat="ecdf"))