无法添加回归线

时间:2021-03-29 18:23:57

标签: r

我是 r 的新手,并试图运行一个散点图,其中添加了一条回归线和映射到颜色的 ID。我试过了:

res.render(‘view’,parameter)

但是当我运行它时不会出现回归线。

我尝试过的另一件事是 ggscatter,我可以使用回归线运行它,但我无法弄清楚如何在该代码中将 ID 映射到颜色。

ggplot(MeanData, aes(x = MeanDifference, y = d, col = ID)) + geom_jitter()+ geom_smooth(method = "lm", se = FALSE) + theme_classic()

谁能建议如何运行散点图,其中包括回归线和将变量映射到颜色?提前致谢!

1 个答案:

答案 0 :(得分:2)

geom_smooth 层将从原始 color 调用中继承 ggplot() 美学,并尝试为每种颜色拟合一条线 - 大概是您的数据,每个点一条线。相反,您需要 (a) 在 aes(color = ID) 层中指定 geom_jitter,而不是原始的 ggplot 调用,或者 (b) 将 aes(group = 1) 放入 geom_smooth所以它知道将所有点组合在一起。其中任何一个都应该有效:

# a
ggplot(MeanData, aes(x = MeanDifference, y = d)) +
  geom_jitter(aes(color = ID)) +
  geom_smooth(method = "lm", se = FALSE) + 
  theme_classic()

# b
ggplot(MeanData, aes(x = MeanDifference, y = d, color = ID)) +
  geom_jitter() +
  geom_smooth(aes(group = 1), method = "lm", se = FALSE) + 
  theme_classic()