使用 ggplot 绘制线条并拟合线性回归线

时间:2021-03-02 05:49:41

标签: r ggplot2 plot dplyr time-series

我生成了一个玩具数据如下:

toy.df <- data.frame(ID = rep(paste("S",1:25, sep = "_") ,4) , x  = rep(seq(1,5), 20), y = rnorm(100), color_code = rnorm(100)
                 ,group = rep(letters[1:4] , 25) )

我想使用 ggplot 生成多条线以及 4 个面中的点,并将线性回归线拟合到每个面中的每组线。

toy.df %>% ggplot(aes(x = x, y = y, group = ID)) +
 facet_wrap( . ~ group, scales = 'free', ncol = 2)+
 geom_point() + 
 geom_line(aes(color = color_code)) +
 geom_smooth(method = 'lm')

但它不会在 x 轴(1 到 5)上生成线

你知道我该如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您将 ID 用作 group,并且每个组仅包含一个观察结果。因此,不可能仅使用一种观察来拟合线性回归。删除 group = ID 就像

library(tidyverse)

toy.df %>% 
  ggplot(aes(x = x, y = y)) +
  facet_wrap( . ~ group, scales = 'free', ncol = 2)+
  geom_point() + 
  geom_smooth(method=lm, se=F, formula = y ~ x)

enter image description here