我已经对这个错误进行了相当多的研究,而在所有其他情况下,当缺少括号或paren时,似乎会出现此错误。但是,我已经扫描了我的代码,我没有看到任何地方。在抛出错误之前,似乎代码没有读取我的完整aes对象:
我正在创建一个函数,它将创建一个ggplot对象,在我的图表上绘制参考线和注释。这是功能:
create_geom_segments <- function(labelx, labely, text_label, color) {
geom_obj <- (
geom_segment(aes(x=0, y=labely, xend =labelx, yend=labely), col = color, linetype = "dashed") +
geom_segment(aes(x=labelx, y=0,xend=labelx, yend=labely), col = color, linetype = "dashed") +
annotate("text", x=labelx, y=labely + 3, label=text_label)
)
return(geom_obj)
}
当我使用通用输入运行时,例如
test <- create_geom_segments(0,10, "test", "red")
我明白了:
Error in geom_segment(mapping = aes(x = 0, y = labely, xend = labelx, :
non-numeric argument to binary operator
我在使用以下函数在函数外成功创建这些对象后构建此函数:
new_graph <- (p + geom_segment(aes(x=0,y = x, xend = days_x, yend =x), col = "red", linetype = 'dashed') + geom_segment(aes(x=days_x, y = 0, xend = days_x, yend = x)
, col = "red", linetype = 'dashed') + annotate("text", x= days_x, y = x + 3, label = text ))
我没有收到任何关于此代码的错误,并且按预期工作。
答案 0 :(得分:2)
完全解决方案,感谢baptiste和joran:
create_geom_segments <- function(labelx, labely, text_label, line_color, xoffset, yoffset) {
geom_obj <- list(
geom_segment(aes_string(x=0, y=labely, xend =labelx, yend=labely), col =
line_color, linetype = "dashed"),
geom_segment(aes_string(x=labelx, y=0,xend=labelx, yend=labely), col =
line_color, linetype = "dashed"),
geom_text(aes_string(x=labelx + xoffset, y=labely + yoffset),
label = text_label, data = data.frame())
)
return(geom_obj)
}
所做的更改: