如何堆叠功能?

时间:2014-09-04 15:37:58

标签: r ggplot2

我有以下代码:

library("ggplot2")

base <- ggplot(data.frame(x = c(-5, 5)), aes(x))

f_sin <- stat_function(fun=sin, colour="red", geom="area", position = 'stack', mapping=aes(fill = "red")) 
f_cos <- stat_function(fun=cos, colour="green", geom="area", position = 'stack', mapping=aes(fill = "green"))

print(base + f_sin + f_cos)

生成此图表的是:

enter image description here

为什么两个功能的区域没有堆叠?

1 个答案:

答案 0 :(得分:1)

通常,您希望在ggplot之外进行计算。这是你想要的吗?

library(reshape)
df <- data.frame(x=seq(-5,5,0.01))
df$sin <- sin(df$x)
df$cos <- cos(df$x)
df <- melt(df,id="x")
ggplot(df, aes(x=x,y=value,fill=variable)) + geom_area(position="stack")

enter image description here

红色区域是sin(x),绿色区域是堆积的&#39; (SIN +余弦)。