ggplot在函数内部不能正常工作,尽管它在函数外部工作



我正在尝试创建一个函数,该函数接受2个参数&为它们输出适当的ggplot。代码可以很好地手动工作,但不知何故,我无法使它在函数包装器中工作。

返回的错误为

Error in eval(expr, envir, enclos) : object 'TimeVector' not found

我试图通过强制未找到的对象来纠正这一点,这些对象被添加到ggplot中,作为字符串。这反过来又以的形式制造了不同的麻烦

Error: Discrete value supplied to continuous scale

删除scale_x_continuous(breaks=0:24)修复了第二个错误,但输出了一个空图,这表明ggplot根本没有提供任何数据。

该数据是按时间分组的交通密度观测的大数据帧。它看起来像这样:

ID                   Road Status                Time Statusint Day  Months Year Weekday
1 Me7war To Sheikh Zayid Orange 2012-10-01 00:03:00         3   1 October   12  Monday
1 Me7war To Sheikh Zayid  Green 2012-10-01 05:00:00         2   1 October   12  Monday
1 Me7war To Sheikh Zayid Yellow 2012-10-01 05:24:00         5   1 October   12  Monday

我试图将"Statusint"变量(状态整数的缩写,范围从1(良好流量)到5(糟糕流量))与"Time"变量进行比较。"Time"的格式是Posix,所以我创建了一个名为"TimeVector"的数字向量,其唯一目的是在ggplot中进行绘图。

功能如下:

Plotroad <- function( roadID , Day ) {
*** Working Code ***
else { 
### THE PROBLEM CODE: Everything below works manually, but returns an error in the function
Roadsubset <- October[October$ID == as.numeric(roadID), ] 
Timesubset <- subset(Roadsubset, format(Roadsubset$Time,'%d') == "Day" )
TimeVector <- as.numeric(gsub(":" , "." , strftime(Timesubset$Time, format="%H:%M")))
ggplot(Timesubset, aes( x = "TimeVector", y = "Timesubset$Statusint")) + geom_point() +  
stat_smooth() + scale_x_continuous(breaks=0:24) 

### The working code: 
Roadsubset <- October[October$ID == as.numeric(roadID), ] 
Timesubset <- subset(Roadsubset, subset = Roadsubset$Day == as.integer(Date) )
TimeVector <- as.numeric(gsub(":" , "." , strftime(Timesubset$Time, format="%H:%M")))
Timesubset$timevector <- TimeVector
print(ggplot( data = Timesubset, aes_string( x = "timevector" , y = "Statusint" )) + geom_point() + stat_smooth()  + scale_x_continuous(breaks=0:24) + labs(list(title = as.character(Timesubset$Road[1]) , x = "Time of Day", y = "Status")))  
}
}

我看到一些建议使用print,因为ggplot不是在命令行中调用的。然而,这并不能修复上述错误。

这是我第一篇关于堆栈溢出的文章,所以如果需要的话,请指出我如何更好地为未来格式化问题。谢谢

除了使用变量名之外,作用域也有问题。GGPlot在全局环境中执行非标准评估,因此函数中定义的任何内容都不能直接访问,除了"数据"参数,因为该参数是显式传递的,而不是通过非标准评估传递的。因此,解决这个问题的一个方法是将变量添加到数据参数中。我创建了一个例子,我认为它模仿了你的问题,但由于我没有你的数据,所以不完全相同:

gg_fun <- function() {
data <- data.frame(a=1:10, b=1:10)
clr <- rep(c("a", "b"), 5)
ggplot(data, aes(x=a, y=b, color=clr)) + geom_point()
}
gg_fun()
# Error in eval(expr, envir, enclos) : object 'clr' not found
gg_fun <- function() {
data <- data.frame(a=1:10, b=1:10)
clr <- rep(c("a", "b"), 5)
data$clr <- clr
ggplot(data, aes(x=a, y=b, color=clr)) + geom_point()
}
gg_fun() # works

在您的情况下,您需要将TimeVector添加到Timesubset(琐碎),然后使用未加引号的aes语法:

ggplot(Timesubset, aes(x=TimeVector, y=Statusint)) ...

最新更新