我需要ggplot()的帮助,这是我第一次使用它。 我有一个定义如下的函数:
myHist <- function(data, varName = "") {
gp <- ggplot(data, aes(data[, varName]))
gp <- gp + geom_histogram(alpha = 1, aes(fill=..count..))
gp <- gp + labs(title = paste("Histogram for ", varName, sep = " "))
gp <- gp + labs(x = varName, y = "N")
gp <- gp + scale_fill_gradient("", low = "blue", high = "red")
gp
}
然后按如下方式使用它:
myHist(data = iris, varName = "Petal.Width")
会出现以下错误:
"Error in eval(expr, envir, enclos) : object 'varName' not found"
任何人都可以帮忙吗?同时调试如果我初始化传递的函数的内部部分的参数工作。但功能本身不起作用
答案 0 :(得分:0)
您需要使用aes_string
,因为您的变量是存储为字符值的函数的输入值。
myHist <- function(data, varName = "") {
gp <- ggplot(data=data, aes_string(varName))
gp <- gp + geom_histogram(alpha = 1, aes(fill=..count..))
gp <- gp + labs(title = paste("Histogram for", varName, sep = " "))
gp <- gp + labs(x = varName, y = "N")
gp <- gp + scale_fill_gradient("", low = "blue", high = "red")
gp}