为什么`cumsum'在ggplot中的组或构面中不起作用? [英] Why `cumsum` doesn't work within groups or facets in ggplot?
问题描述
x <- data.frame(A=replicate(200,sample(c("a","b","c"),1)),X=rnorm(200))
ggplot(x,aes(x=X,color=A)) + stat_bin(aes(y=cumsum(..count..)),geom="step")
如您所见,cumsum
可跨组&方面.我想知道为什么会这样吗?显然,..count..
是在组内完成的,为什么当将cumsum
应用于..count..
时却没有? ggplot是否在内部将所有..count..
归入一个向量,然后对其应用cumsum
?
As you can see, cumsum
work across groups & facets. I am wondering why it does that? Clearly ..count..
is done within groups, why cumsum
is not when applied on to ..count..
? Does ggplot internally cat all ..count..
into a vector and then apply cumsum
to it?
如何在不进行预处理的情况下正确解决该问题,例如使用plyr
?
How to correctly resolve it without pre processing, e.g. using plyr
?
我不介意geom
不是step
,只要图形是累积图,它就可以是line
甚至是bar
.
And I don't mind geom
is not step
, it can be line
or even bar
as long as the graph is a cumulative plot.
推荐答案
这是我用一行代码(ddply和mutate)处理此问题的方法:
Here's how I handle this with one line of code (ddply and mutate):
df <- data.frame(x=rnorm(1000),kind=sample(c("a","b","c"),1000,replace=T),
label=sample(1:5,1000,replace=T),attribute=sample(1:2,1000,replace=T))
dfx <- ddply(df,.(kind,label,attribute),mutate,cum=rank(x)/length(x))
ggplot(dfx,aes(x=x))+geom_line(aes(y=cum,color=kind))+facet_grid(label~attribute)
这篇关于为什么`cumsum'在ggplot中的组或构面中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!