I want to use the variable mapped to y in geom_hline(). Basically, I want to achieve the same behavior as in:
ggplot(mtcars, aes(x = hp, y = qsec)) +
geom_point() +
geom_hline(yintercept = mean(mtcars$qsec))
But I don’t want to "repeat" mtcars$qsec for the yintercept parameter.
I tried using something like yintercept = mean({{ y }}) but this gives me the "Error: object ‘y’ not found". To be honest, I do not fully understand when we can use these curly brackets.
Is there a way to do this? Thanks for your help!
>Solution :
geom_hline does not have access to the y aesthetic. You could do:
ggplot(mtcars, aes(x = hp, y = qsec)) +
geom_point() +
geom_hline(aes(yintercept = mean(qsec)))
From the comments, it appears that the issue is having to repeat the code for several geom_hlines. One can actually pass several values to geom_hline in a single call, so the easiest way to do this might be to summarize the data being passed to a single geom_hline call:
ggplot(mtcars, aes(x = hp, y = qsec)) +
geom_point() +
geom_hline(data = . %>%
reframe(mean = mean(qsec),
sd = sd(qsec),
yintercept = seq(mean - 2*sd, mean + 2*sd, sd),
color = factor(c('-2sd', '-1sd', 'mean', '+1sd', '+2sd'),
c('-2sd', '-1sd', 'mean', '+1sd', '+2sd'))
), aes(yintercept = yintercept, color = color)) +
scale_color_manual(NULL, values = c('#FF000040', '#FF000080', 'red',
'#FF000080', '#FF000040'))


