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