【发布时间】:2014-01-17 16:48:35
【问题描述】:
我正在尝试创建一个函数,该函数接受 2 个参数并为它们输出适当的 ggplot。该代码手动完美运行,但不知何故我无法使其在函数包装器中运行。
返回的错误是
Error in eval(expr, envir, enclos) : object 'TimeVector' not found
我尝试通过强制将未找到的 objects 作为字符串添加到 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(糟糕流量)的状态整数的缩写。 “时间”被格式化为 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")))
}
}
我看到一些 advice 建议使用 print,因为 ggplot 不是在命令行中调用的。但是,这并不能解决上述错误。
这是我关于堆栈溢出的第一篇文章,所以如果需要,请指出我如何更好地格式化未来的问题。谢谢。
【问题讨论】:
-
tl;dr,但您似乎在寻找
aes_string? -
@Roland Danke, aber 这又会产生一个新错误:
Error in parse(text = x)[[1]] : subscript out of bounds -
试着把这个
aes( x = "TimeVector", y = "Timesubset$Statusint"))改成aes_string( x = "TimeVector", y = "Statusint"))我相信你不应该继续在aes() 调用中添加数据引用。 Here is a similar question -
尝试只使用一个包含所有数据的
data.frame和long format。检查此Question 以了解如何制作可重现的示例。 -
@MartínBel 做这两件事帮助很大,谢谢
标签: r function debugging ggplot2