Search code examples
rggplot2smoothing

error in stat_smooth because object is not found


I would like to use stat_smooth and the number of points at which to evaluate smoother should be the number of rows in the dataset.

data <- tibble(x=runif(20), y=runif(20))

data %>% 
  mutate(m=n()) %>% 
  ggplot(data=.) + 
  geom_point(aes(x = x, y = y), colour = 'red') +
  geom_smooth(aes(x = x, y = y), method = NULL, se = TRUE) +
  stat_smooth(aes(x = x, y = x), n=min(m))

Unfortunately I will get the error

Error: object 'm' not found

Thanks for any hints!


Solution

  • This is an issue with the scope of ggplot2 in general. ggplot is not able to see variables from your dataframe outside of aes().
    I can think of three options to resolve your issue:

    1. Do what @nightstand already recommended in a comment (and what I'd recommend as well).
    data %>%
    ggplot() + 
      geom_point(aes(x = x, y = y), colour = 'red') +
      geom_smooth(aes(x = x, y = y), method = NULL, se = TRUE) +
      stat_smooth(aes(x = x, y = y), n=nrow(data))
    
    1. If you are really attached to your m-variable you can call make a reference to the dataframe.
    data <- data %>%
      mutate(m=n())
    ggplot(data = data) + 
      geom_point(aes(x = x, y = y), colour = 'red') +
      geom_smooth(aes(x = x, y = y), method = NULL, se = TRUE) +
      stat_smooth(aes(x = x, y = y), n=min(data$m))
    
    1. Or one possibility if you really just want min(m) without data$m would be to calculate m first, then use with() use it in ggplot.
    data <- data %>%
      mutate(m=n())
    with(data,
    ggplot() + 
      geom_point(aes(x = x, y = y), colour = 'red') +
      geom_smooth(aes(x = x, y = y), method = NULL, se = TRUE) +
      stat_smooth(aes(x = x, y = y), n=min(m))
    )