[英]Categorize a continuous predictor variable and calculate proportion of binary outcome
[英]Visualizing the relationship between a continuous predictor and a categorical outcome
我正在嘗試可視化連續預測變量(范圍0-0.8)和離散結果(計數變量,可能的值:0、1、2)之間的關系。
有很多選項可以在x軸上顯示離散變量,而在y軸上顯示連續變量(例如,點圖,小提琴,箱形圖等)。 這些選項顯示了連續預測變量的分布,其中每組離散變量的中心度都在其中。 但是,這不會顯示我要描述的消息。 我想顯示隨着連續變量分數的增加而使離散變量的值增加的可能性。
我嘗試使用geom_smooth進行此操作,但是由於結果是離散的,因此這似乎具有誤導性:
p <- ggplot(pheno, aes(adhdanx, polye))
p + geom_smooth(method = "lm", colour = "#007ea7", size = 0.5, fill = "#007ea7")
我在R工作。歡迎提出所有建議。
據我所知,對於僅具有分類預測變量的線性回歸模型,不可能存在線性擬合。 您可以繪制每個點 。 在這里,我將使用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)
從此箱圖中,您可以看到各個Species
中Petal.width
的分布以及正相關。 對於定性預測變量,該變量將編碼為:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.