2017-06-19 91 views
1

我在一个函数内使用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在函数中以这种方式调用数据是不可能的?

回答

1

aes_string替换整个字符串,而不只是变种。您可以使用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") 

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