如何编写一个将NULL传递给ggplot而不会出现美学错误的函数

时间:2017-10-08 14:46:44

标签: r ggplot2 null aesthetics

我正在尝试编写一个创建绘图的函数并遇到一个我不理解的错误。这是一个简化的例子。

可重复示例:

library (ggplot2)
# Sample data
xdata = 0:20
ydata = 20:40
dat <- data.frame(xdata, ydata)

# This works
line_p <- ggplot(dat, aes(x = xdata, y = ydata, group = NULL, color = NULL)) + geom_line()
line_p

我希望以下方法有效,但会出现美学错误,但在这种情况下,x和y变量的长度相同。问题似乎是组和颜色的默认值为NULL。我尝试显式传递NULL以及aes_group和aes_color作为函数变量,但这也没有用。

# Using a function doesn't work:

# create function
line_function <- function(mydata     = dat,
                          xinput     = x,
                          yinput     = y,
                          aes_group  = NULL,
                          aes_color  = NULL,
                          ...) {

  lineplot <- ggplot(dat, aes(x = xinput, y = yinput, group = aes_group, color = aes_color)) + geom_line()
}


# test the function
line_test_p <- line_function(
  mydata = dat,
  xinput = xdata,
  yinput = ydata
)

line_test_p

使用显式输入进行测试

# test the function again with explicit NULL inputs

line_test2_p <- line_function(
  mydata    = dat,
  xinput    = xdata,
  yinput    = ydata,
  aes_group = NULL,
  aes_color = NULL
)

line_test2_p

是否不可能编写一个泛型函数,其中ggplot将解释NULL值,如在没有函数的情况下工作的示例,或者我是否遗漏了其他内容?

谢谢!

1 个答案:

答案 0 :(得分:1)

简而言之,您应该检查aes_string以编程方式创建美学映射。它允许您使用存储字符串的变量名称创建美学映射。这样,很容易将列名作为参数传递给函数并创建相应的图。

以下版本的函数适用于我:

# create function
line_function <- function(mydata     = dat,
                          xinput     = "x", # note the defaults are
                          yinput     = "y", # strings here
                          aes_group  = NULL,
                          aes_color  = NULL,
                          ...) {

  ggplot(mydata, # this should be the argument, not the global variable dat
         # now we create the aes binding with aes_string
         aes_string(x = xinput,
                    y = yinput,
                    group = aes_group,
                    color = aes_color)) +
    geom_line()
}

现在您可以使用该功能创建示例:

# test the function
line_test_p <- line_function(
  mydata = dat,
  xinput = "xdata", # note the strings
  yinput = "ydata"
)

# test the function again with explicit NULL inputs
line_test2_p <- line_function(mydata    = dat,
                              xinput    = "xdata", # and strings here
                              yinput    = "ydata",
                              aes_group = NULL,
                              aes_color = NULL)

事情应该适合你。再次,请查看documentation,因为有不同的方法可以实现这一点,您可能更喜欢不同的方式或偏好。

相关问题