Non-numeric function argument of binary operator aes

I've done quite a bit of research on this error, and in all other cases it seems that this error appears when a parenthesis or pairs are missing. However, I cleaned up my code and I can't see anything. The code doesn't seem to read my full aes object before throwing the error:

I am creating a function that will create a ggplot object that draws pivot lines and annotation on my chart. Here's the function:

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) 



When I run this with generic inputs like

test <- create_geom_segments(0,10, "test", "red")


I get:

Error in geom_segment(mapping = aes(x = 0, y = labely, xend = labelx,  : 
non-numeric argument to binary operator


I create this function after creating these objects successfully outside the function using this:

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 ))


I had no errors with this code and it worked as expected.


source to share

1 answer

Full solution here, thanks to baptist and 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()) 


Changes made:

Changed to use syntax + between geom_segment objects to create a list. FYI when calling these objects from the returned object, I used the result [[i]]. This removed the original error I was reporting. The next question was that it didn't recognize my labelx and labely input functions. Changed from aes () to aes_string () so that the function recognizes function inputs. Finally, the annotation does not recognize input functions. Changed for geom_text as above to fix. (also added offsets to the function so my labels weren't on top of the lines.


All Articles