ggplot2对象无法在修改时复制?

时间:2019-01-30 17:06:28

标签: r ggplot2

我有一个对象(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

我的问题是:

  1. 如何重写aes_changer修改原始的line_and_shape
  2. 为什么aes_changer / line_and_shape会发生这种情况,而triple / a却不会发生?

0 个答案:

没有答案