我在一个函数内使用ggplot2并试图为y轴创建平均线。我遇到了麻烦,看起来是因为定义y轴的变量是函数参数之一,我不能直接在ggplot中调用它。通过函数传递ggplot并引用一个参数
library(ggplot2)
west <- data.frame(
spend = sample(50:100,50,replace=T),
trials = sample(100:200,50,replace=T),
courts = sample(25:50,50,replace=T),
country = sample(c("usa","canada","uk"),50,replace = T)
)
这里的功能的基本版本,我的工作:
ggfun <- function(data, xvar, yvar) {
newplot <- ggplot(data=west, aes_string(x=xvar, y=yvar)) +
geom_point(shape=21, fill="blue") +
newplot
}
并调用如下工作:
ggfun(west, "spend", "trials")
但是,当我尝试在geom_hline增加,我收到一个错误:
ggfun <- function(data, xvar, yvar) {
newplot <- ggplot(data=west, aes_string(x=xvar, y=yvar)) +
geom_point(shape=21, fill="blue") +
geom_hline(yintercept=mean(yvar))
newplot
}
ggfun(west, "spend", "trials")
Warning messages:
1: In mean.default(data$yvar) :
argument is not numeric or logical: returning NA
2: Removed 1 rows containing missing values (geom_hline).
使用ggplot在函数中以这种方式调用数据是不可能的?