首页 > 解决方案 > 使用 ggplot 绘制线并拟合线性回归线

问题描述

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

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)上生成线条

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

标签: rggplot2plotdplyrtime-series

解决方案


您正在使用 ID asgroup并且每个组仅包含一个观察值。因此,仅使用一个观察值来拟合线性回归是不可能的。删除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)

在此处输入图像描述


推荐阅读