我有一个对象(line_and_shape
),该对象由ggplot2
层的列表组成。我有一个函数(aes_changer
)可以修改line_and_shape
中的图层,但是我没有明确覆盖line_and_shape
。但是,运行函数后,line_and_shape
的行为就像被覆盖一样。最好用一个示例来显示:
library(ggplot2)
# An object with some ggplot2 layers that can be added to any plot
line_and_shape <- list(
geom_path(data=data.frame(x = c(19, 18, 20, 18), y = c(20, 21, 18, 17)), aes(x = x, y = y)),
geom_hline(yintercept = 16)
)
# A function that iterates over a list of ggplot2 layers and modifies their aes
aes_changer <- function(layer_object, colour = "green", alpha = 1){
for(ii in 1:length(layer_object)){
layer_object[[ii]]$aes_params$colour <- colour
layer_object[[ii]]$aes_params$alpha <- alpha
}
return(layer_object)
}
# A ggplot
ggplot(mtcars) +
aes(x = mpg, y = qsec) +
geom_point()
# (1) A ggplot, with portable layers added. Note that the lines are black
ggplot(mtcars) +
line_and_shape +
aes(x = mpg, y = qsec) +
geom_point()
# (2) A ggplot with portable layers added, but altered so that the lines are red
ggplot(mtcars) +
aes_changer(line_and_shape, colour = "red") +
aes(x = mpg, y = qsec) +
geom_point()
# (3) The same code as (1), but the lines are red, not black!
ggplot(mtcars) +
line_and_shape +
aes(x = mpg, y = qsec) +
geom_point()
# Compare to:
triple <- function(x) {
x <- 3*x
x
}
a <- 5
triple(a)
a
我的问题是:
aes_changer
来不修改原始的line_and_shape
?aes_changer
/ line_and_shape
会发生这种情况,而triple
/ a
却不会发生?