Reputation: 395
I have generated a toy data as following:
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) )
I would like to use ggplot to generate multiple lines as well as points in 4 facets and fit a linear regression line to each the group of lines in each facet.
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')
But it does not generate the lines over the x axis (1 to 5)
Do you have any idea how can I fix this?
Upvotes: 0
Views: 347
Reputation: 8136
You are using ID as group
and each group contains only one observation. So, it is not possible to fit linear regression using only one observation. Removing group = ID
works fine like
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)
Upvotes: 1