R 中 geom_abline() 的奇怪行为

标签 r geom

我正在使用此代码:

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

我得到了这个图表:

enter image description here

然后我用 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() 的线去了哪里?

enter image description here

然后我切换顺序并小心 + 符号...

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

两条线路都回来了。所以 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) 
  

enter image description here

geom_smooth() 存在,但 abline 不存在。我真的对这种行为感到困惑。我真的只想要 abline 而不是平滑的,但这不起作用:

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

enter image description here

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

最佳答案

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

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

输出:

enter image description here

关于R 中 geom_abline() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71385017/

相关文章:

r - 如何将矩阵转换为 R 中的不同矩阵?

r - Spotfire - 所有输出均已使用脚本 R 删除

R:创建表达式向量的最简单方法(单行?)是什么?

r - 建立一个新的 geom_hurricane

r - 如何将 geom_boxplot 和 geom_point 与每组不均匀的观察结果对齐?

r - 如何使用 R 绘制世界地图

r - 在 R 中使用带有 phylo 对象(无根树)的切割树

r - 使用 R 将大型文本文件构建为数据框