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

R weird behavior with geom_abline()

I am using this code:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1) +  
  geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')

And I get this graph:

enter image description here

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

Then I comment out the middle line of code with command + shift + c

ggplot(mtcars, aes(x = wt, y = mpg)) +
  # geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1) +  
  geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')
   

I get a graph without any lines. Where did the line from geom_abline() go?

enter image description here

I then switch the order and be careful with the + signs…

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed') +
  geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1) 

enter image description here

Both lines are back. So the code for geom_abline() seemed fine, right?

So I then comment out the middle line:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  # geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed') +
  geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1) 
  

enter image description here

The geom_smooth() is there but not the abline. I’m really confused by this behavior. I really just want the abline and not the smooth but this doesn’t work:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed') 

enter image description here

There must be a simple reason. But also – why is the behavior inconsistent? It feels like a bug because the same code in one place seems to work and in another place doesn’t.

>Solution :

You can use this code to plot only the abline:

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_blank() +   
  geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')

Output:

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