Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access a mapped variable from aes() in geom_hline()?

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

mtcars plot

But I don’t want to "repeat" mtcars$qsec for the yintercept parameter.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

enter image description here

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading