使用ggplot绘制纵向趋势的总体趋势

时间:2020-05-03 17:26:24

标签: r ggplot2 plot

我想绘制纵向数据的总体趋势。我正在使用sleepstudy包中的lme4数据来演示我的问题。

 library("lme4")
 library("ggplot2")
    p1 <- ggplot(data = sleepstudy, aes(x = Days, y = Reaction, group = Subject))
    p1 + geom_line() + geom_point(aes(col = Subject) ,size=2)

当我绘制每个人的纵向轨迹时,我得到了这个图 enter image description here

在这里,我有兴趣根据所有主题找到总体趋势。对于基于上述图的示例,我们可以看到总体上呈上升趋势。通常,这种趋势可以是线性,二次曲线等。这是绘制总体趋势的任何方法吗?

我尝试过这个。但是我得到了每个主题的平滑曲线,而不是总体趋势

p1  + geom_point() +  geom_smooth(method = "lm") 

enter image description here

有人可以帮我解决这个问题吗?

谢谢

1 个答案:

答案 0 :(得分:1)

不知道我是否正确理解:

library("lme4")
library("ggplot2")
ggplot(data = sleepstudy, aes(x = Days, y = Reaction))+
  geom_point(aes(colour = Subject), alpha = .3)+
  geom_smooth()+
  theme(legend.position = "none")

enter image description here

如您所见,您将拥有loess功能:

> geom_smooth()` using method = 'loess' and formula 'y ~ x'

如果您需要lm,只需在method中指定参数geom_smooth

library("lme4")
library("ggplot2")
ggplot(data = sleepstudy, aes(x = Days, y = Reaction))+
  geom_point(aes(colour = Subject), alpha = .3)+
  geom_smooth(method = "lm")+
  labs(title = "Linear Model (LM)")+
  theme(legend.position = "none")

结果:

enter image description here

相关问题