geom_abline() 的 R 怪异行为

R weird behavior with geom_abline()

我正在使用此代码:

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

我得到这张图:

然后我把中间那行代码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')
   

我得到一个没有任何线条的图表。来自 geom_abline() 的行去哪儿了?

然后我调换顺序并注意 + 号...

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) 

两条线都回来了。所以 geom_abline() 的代码看起来不错,对吧?

所以我接着把中间那行注释掉:

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) 
  

geom_smooth() 在那里,但 abline 没有。我真的对这种行为感到困惑。我真的只想要 abline 而不是 smooth 但这行不通:

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

一定有一个简单的原因。而且 - 为什么行为不一致?感觉像是一个错误,因为相同的代码在一个地方似乎可以工作,而在另一个地方却不行。

您可以使用此代码仅绘制 abline:

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

输出: