【问题标题】:Using functional programming with ggplot使用带有 ggplot 的函数式编程
【发布时间】:2018-02-26 20:49:39
【问题描述】:

我真的不习惯使用函数,我无法让 ggplot 使用它们。

由于某种原因,这可行:

function_factory <- function(x){
  times <- function(y) x * y
} 

simple_application <- function(z1, z2){
  times_z1 <- function_factory(z1)
  times_z2 <- function_factory(z2)
  times_z1(3) * times_z2(3)
}

simple_application(3, 3)

但这不是:

plot_times <- function(z1, z2){
  times_z1 <- function_factory(z1)
  times_z2 <- function_factory(z2)
  library(ggplot2)
  ggplot(data = data.frame(x = 0), mapping = aes(x = x)) + 
    stat_function(fun = "times_z1", xlim = c(1, 1000)) +
    stat_function(fun = "times_z2", xlim = c(1, 1000))
}


plot_times(3, 4)

我刚刚收到以下错误:

> plot_times(3, 4)
Warning messages:
1: Computation failed in `stat_function()`:
object 'z1' not found 
2: Computation failed in `stat_function()`:
object 'z2' not found 

我还有一些问题,但我希望如果我能解决这个问题,我也能解决我自己的问题。 ' 我很确定这与环境有关,但我不知道如何解决它。

请注意,如果没有函数工厂,这会很好地工作:

times_three <- function(x) 3 * x
times_four <- function(x) 4 * x
ggplot(data = data.frame(x = 0), mapping = aes(x = x)) + 
  stat_function(fun = "times_three", xlim = c(1, 1000)) +
  stat_function(fun = "times_four", xlim = c(1, 1000))

【问题讨论】:

  • 在最后一段代码中,times_threetimes_four 是函数。在 plot_times 函数中,有对象。我怀疑 stat_function 需要一个函数来传递给fun 参数。
  • 比预期简单:只需去掉引号。 fun = times_z1 工作。
  • 谢谢 ira 和 Rui Barradas。哇,它确实有效地删除了引号。这让我困扰了好几个小时。
  • 我还是不明白为什么。正如我在第一段代码中展示的那样,我可以使用 times_z1 作为函数。
  • 这与一些评估有关。我无法回答,因为我真的不太了解那个主题。

标签: r ggplot2 functional-programming


【解决方案1】:

stat_function 发送的不是"function",而是得到get("function") 的结果。例如,用stat_function(fun = get("times_z1"), xlim = c(1, 1000)) 代替stat_function(fun = "times_z1", xlim = c(1, 1000))

plot_times <- function(z1, z2){
  library(ggplot2)
  times_z1 <- function_factory(z1)
  times_z2 <- function_factory(z2)
  ggplot(data = data.frame(x = 0), mapping = aes(x = x)) + 
    stat_function(fun = get("times_z1"), xlim = c(1, 1000)) +
    stat_function(fun = get("times_z2"), xlim = c(1, 1000))
}

结果:

plot_times(3, 4)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多