R 如何编写一个将NULL传递给ggplot的函数而不产生错误
我正试图编写一个函数来创建绘图,但遇到了一个我不理解的错误。这里是一个简化的例子 可复制示例:R 如何编写一个将NULL传递给ggplot的函数而不产生错误,r,ggplot2,null,aesthetics,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()
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
库(ggplot2)
#样本数据
扩展数据=0:20
ydata=20:40
dat简而言之,您应该检查一下如何以编程方式创建美学映射。它允许您使用存储字符串的变量名称创建美观映射。这样,就很容易将列名作为参数传递给函数并创建相应的绘图
以下版本的函数适用于我:
# 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()
}
#创建函数
安德鲁,就这样,谢谢。阅读文档后最简单的更改是将lineplot行更改为:lineplot
# 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
# 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)