通过函数传递ggplot并引用参数

时间:2017-06-19 23:03:46

标签: r ggplot2

我在一个函数中使用ggplot2并尝试为y轴创建平均线。我似乎遇到了麻烦,因为定义y轴的变量是函数args之一,我不能直接在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在函数内以这种方式调用数据?

2 个答案:

答案 0 :(得分:1)

yvar是一个字符串,它的工作方式与您执行此操作完全相同,而不是在函数中:

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() + 
  geom_hline(yintercept = mean("mpg"))
Warning messages:
1: In mean.default("mpg") :
  argument is not numeric or logical: returning NA
2: Removed 1 rows containing missing values (geom_hline). 

我建议预先计算均值,这样就可以将值传递给yintercept

ggfun <- function(data, xvar, yvar) {
  mean_yvar = mean(data[[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")
# works fine

答案 1 :(得分:1)

aes_string替换整个字符串,而不仅仅是var。您可以使用paste创建正确的字符串:

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=data, aes_string(x=xvar, y=yvar)) +
    geom_point(shape=21, fill="blue") + 
    geom_hline(aes_string(yintercept = paste0('mean(', yvar, ')')))

  newplot  
}
ggfun(west, "spend", "trials")