Home > Net >  How to avoid "object not found" error with geom_abline?
How to avoid "object not found" error with geom_abline?

Time:08-05

I am trying to plot lines from a data frame with columns indicating the slope and intercept, but keep on getting an "object not found" error. Here is a reproducible example:

library(tidyverse)

df <- tibble(intercept = 1,
             slope = 0.5)

df %>% 
  ggplot()  
  geom_abline(slope = slope, intercept = intercept)
#> Error in geom_abline(slope = slope, intercept = intercept): object 'slope' not found

I recognize that I must be missing something fairly rudimentary about the operation of geom_abline, but -- based on the documentation -- it's not clear to me what I'm missing. So, my questions are: (1) why does the code yield this error, and (2) how can I plot the data using ggplot?

CodePudding user response:

Your approach would work if you put the intercept and slope in the aesthetics, e.g.

df %>% 
  ggplot()  
  geom_abline(aes(slope = slope, intercept = intercept))

If you don't want to use the aesthetics, you need to reference the column of the dataframe:

df %>% 
  ggplot()  
  geom_abline(slope = df$slope, intercept = df$intercept)
  • Related