简体   繁体   中英

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:

在此处输入图像描述

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?

在此处输入图像描述

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) 

在此处输入图像描述

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) 
  

在此处输入图像描述

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

在此处输入图像描述

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.

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM