If i pass a value to ggplot, it is stored as a reference so if it gets modified, the plot is changed as well. However, this only happens if it is given to the aes function, not the geom_hline in my example.
library(ggplot2)
# The line is at 10
value <- 10
pl <- ggplot() + geom_hline(yintercept=value)
value <- 0
pl
# The line is at 0
value <- 10
pl <- ggplot() + geom_hline(aes(yintercept=value))
value <- 0
pl
I believe this question is related to this one, but I don't understand what I can do to avoid this behaviour. Can I force ggplot to make a copy of the data?
Regarding the use case, imagine I have a loop to plot many separate figures and value
changes at each iteration of the loop.
plot_list <- NULL
for (value in 1:10) {
# The title goes from 1 to 10 but all the lines are on 10.
plot_list[[value]] <- ggplot() + geom_hline(aes(yintercept=value)) + labs(title=value)
}
plot_list