问题描述
如果您阅读ggplot
的stat_function
帮助,则可以看到:
If you read ggplot
's stat_function
help, you can see that :
- 组
- y
但是没有如何使用它的示例.
But there is no example on how to use it.
就我而言,我想访问自定义函数中的组" ae.这是我不幸的尝试(只能绘制一条曲线,而不是每组绘制1条曲线):
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))
奇怪的是,我无法使调试器在log.test
中运行,所以我不知道哪个变量可用.
Something odd is that I cannot get the debugger to work inside log.test
, so I don't know which variable is available.
请注意,这将与geom_abline(aes(intercept=A,slope=B,color=myGroup))
(而不是stat_function(...)
)完美配合.
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.
推荐答案
尝试一下:
df = data.frame(A=1:10, B=rep(seq(1,1.8,by=0.2), 2),
myGroup=c(rep("Group1", 5), rep("Group2", 5))) #you don't even need to define df here because you're passing all the arguments inside mapply
log.test = function(x,A,B) {
y = log(A + x*B)
return(y)
}
ggplot(data.frame(x = c(0, 50)), aes(x)) +
mapply(function(A, B, myGroup) {
stat_function(fun = log.test, args = list(A = A, B = B), col = myGroup)
},
# enter A, B, and colors here
A = c(0, 10),
B=rep(seq(1,1.8,by=0.2), 2),
myGroup=c(rep("red", 5), rep("green", 5)))
这篇关于使用ggplot stat_function"group"在自定义函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!