If you read ggplot
's stat_function
help, you can see that :
stat_function understands the following aesthetics (required aesthetics are in bold):
- group
- y
But there is no example on how to use it.
In my case, I want to access the "group" aes inside a custom function. Here is my unfortunate try (which only plot one curve, not 1 per group):
df = data.frame(A=1:10, B=rep(seq(1,1.8,by=0.2), 2),
myGroup=c(rep("Group1", 5), rep("Group2", 5)))
log.test = function(x, data, ...) {
y = log(data$A + x*data$B)
return(y)
}
ggplot(df) +
xlim(0,50) + ylim(0,50) +
labs(x="time", y="Y", color="Group") +
stat_function(aes(group=myGroup), fun=log.test, args=list(data=df))
Something odd is that I cannot get the debugger to work inside log.test
, so I don't know which variable is available.
Note that this would work perfectly with geom_abline(aes(intercept=A,slope=B,color=myGroup))
instead of stat_function(...)
.
I may have a big misunderstanding here, but I cannot manage to find it.