Как я знаю, для модели линейной регрессии только с категориальным предиктором не может быть соответствия линии. Вы можете нарисовать каждую точку . Здесь я бы использовал iris
набор данных.
library(tidyverse)
as_tibble(iris)
#> # A tibble: 150 x 5
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <dbl> <dbl> <dbl> <dbl> <fct>
#> 1 5.1 3.5 1.4 0.2 setosa
#> 2 4.9 3 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa
#> 7 4.6 3.4 1.4 0.3 setosa
#> 8 5 3.4 1.5 0.2 setosa
#> 9 4.4 2.9 1.4 0.2 setosa
#> 10 4.9 3.1 1.5 0.1 setosa
#> # ... with 140 more rows
Рассмотрим регрессионную проблему Petal.width ~ Species
.
iris %>%
ggplot() +
aes(x = Species, y = Petal.Width, colour = Species) +
geom_boxplot(show.legend = FALSE)

Из этого прямоугольника вы можете увидеть распределение Petal.width
в каждом Species
и положительные отношения. Для качественного предиктора переменная будет закодирована как:
contrasts(iris$Species)
#> versicolor virginica
#> setosa 0 0
#> versicolor 1 0
#> virginica 0 1
так что модель становится

, где

и

Таким образом, каждое установленное значение станет

из этих оценок
lm(Petal.Width ~ Species, data = iris)
#>
#> Call:
#> lm(formula = Petal.Width ~ Species, data = iris)
#>
#> Coefficients:
#> (Intercept) Speciesversicolor Speciesvirginica
#> 0.246 1.080 1.780
С этими фактами, как уже упоминалось, на графике можно нарисовать каждое подходящее значение.
С lm()
:
iris %>%
select(Species, Petal.Width) %>% # just for clarity
mutate(pred = lm(Petal.Width ~ Species)$fitted.values) %>% # linear regression
ggplot() +
aes(x = Species, y = Petal.Width) +
geom_point() +
geom_point(aes(x = Species, y = pred), col = "red", size = 3) # fitted values

В качестве альтернативы, отметив, что каждое установленное значение равно среднее значение выборки ,
iris %>%
select(Species, Petal.Width) %>%
group_by(Species) %>% # for each category
mutate(pred = mean(Petal.Width)) %>% # sample mean of response in each category
ggplot() +
aes(x = Species, y = Petal.Width) +
geom_point() +
geom_point(aes(x = Species, y = pred), col = "red", size = 3)
