我正在使用此代码:
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 而不是平滑的,但这不起作用:
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')
输出:
关于R 中 geom_abline() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71385017/