Home > Back-end >  R weird behavior with geom_abline()
R weird behavior with geom_abline()

Time:03-08

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

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.

CodePudding user response:

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

  • Related