The issue is that all the stat_function
s you are refer to the same i
variable. And as a consequence, each function you add will overlay perfectly with the others.
The solution is to reassign the variable in a local scope, to make a local copy for each iteration:
p1 = ggplot(data.frame(x = 1 : 200)) + aes(x)
for (i in 1:10){
p1 = local({
j = i
p1 + stat_function(fun = function(x) x + j * 3, col = j)
})
}
To make matters more confusing, you don’t actually have to give the local variable a new name; you could just as easily have written i = i
, and continued to use i
. The reason is that this assignment will generate a new local variable i
that masks the non-local variable i
. I hope we can agree that writing such code is confusing, and a bad idea.
I’ve also taken the liberty of simplifying your code slightly by moving the data x
out of the stat_function
, and into the ggplot
object directly.
However, it is altogether cleaner not to use a loop and reassignment here. Instead you can use lapply
or map
(from the purrr package):
p1 = ggplot(data.frame(x = 1 : 200)) +
aes(x) +
map(
1 : 10,
~ stat_function(fun = function (x) x + .x * 3, color = .x)
)
This is shorter, more readable (it focuses on the “what” rather than the “how”, i.e. the mechanics of the loop), and it uses a single assignment.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…