我正在使用 ggplot 來可視化許多線性回歸,并按組進行分面。我希望 geom_smooth() 能夠在 P < 0.05 時以一種顏色顯示趨勢線,在 P < 0.10 時以另一種顏色顯示,在 P ≥ 0.10 時完全不顯示。
我設法用一個回圈從lm()中提取每個回歸的P值,然后將它們與用于繪圖的資料連接起來。然后我添加了另一列顏色名稱,以傳遞給 aes(),由 P 值有條件地決定,并使用 scale_color_identity() 來實作我的目標。
這里有一個例子:
library(tidyverse)
#make mtcars a tibble and cyl a factor, for convenience。
mtcars1 <- as_tibble(mtcars) %>% dplyr。 :mutate(cyl = as. factor(cyl))。
#initialize a list to store p-values from lm() for each level of factor。
p. list < -向量(mode = "list"/span>。 length = length(levels(mtcars1$cyl)))
names(p. list) <- levels(mtcars1$cyl)
#loop to calculate p-values for each level of mtcars$cyl.
for(i in seq_along(levels(mtcars1$cyl)))>
mtcars. sub <- mtcars1 %>% dplyr:: filter(cyl == levels(. $cyl)[i])。
lm.pval <- mtcars.sub %>%
dplyr::distinct(cyl) %>;%
dplyr::mutate(P =)
summary(lm(mpg ~ disp, data = mtcars. sub))$coefficients[/span>2, 4] ##extract P-value
)
p.list[[i] <- lm.Pval
} lm.pval
#join p-values to dataset and add column to use with scale_color_identity()。
mtcars. p <- mtcars1 %>% dplyr:: left_join(dplyr::bind_rows(p。 list, . id = " cyl")。 由= " cyl") %> %
dplyr::mutate(p. color = ifelse(P < 0。 05, "black",
ifelse(P < 0. 10, "lightblue"。 NA)))
#plot。
ggplot(data = mtcars. p, aes(x = disp。 y = mpg))
geom_smooth(method = "lm",
se = FALSE,
aes(color =p.color)
geom_point()
scale_color_identity(name = NULL,
na.translate = FALSE,
標簽 = c("P < 0。 05", "P < 0.10"),
guide = "legend")
facet_wrap(~cyl。 天平= "free")
對于應該相對容易的事情,這似乎有太多的初始步驟。這些步驟是否有必要,或者是否有更有效的方法來做這件事?ggplot或其他軟體包能否自己完成這個任務,而不必先從lm()中提取p值?
uj5u.com熱心網友回復:
我們可以用group by操作來簡化步驟,也可以用broom的tidy來代替提取每個組件,輸出可以是一個tibble。
library(broom)
library(dplyr)
library(tidyr)
mtcars1 %>%
group_by(cyl) %>%
summarise(out = list(tidy(lm(mpg ~ disp。 資料= cur_data()))) %> %
unnest(OUT)
輸出
# A tibble: 6 x 6
圓柱項估計值 std.error 統計學 p.value
<fct> < chr> <dbl> <dbl> < dbl> <dbl>
1 4 (Intercept) 40. 9 3.59 11.4 0.00000120[/span>] 。
2 4 disp -0。 135 0.0332 -4.07 0.002783 6 (截距) 19。 1 2.91 6.55 0.00124
4 6 disp 0. 00361 0.0156 0.232 0.826[/span]。
5 8 (截距) 22。 0 3.35 6.59 0.0000259[/span
6 8 disp -0. 0196 0.00932 -2.11 0.0568
uj5u.com熱心網友回復:
在指定了你的回歸函式之后,你可以在ggplot中包含直線函式:
myline< -lm(mpg ~ disp, data = mtcars)
ggplot(data = mtcars。 aes(x = disp, y = mpg))
geom_abline(斜率= coef(myline)[[2]]/span>。 攔截= coef(myline) [[1]]/span>。 color='blue)
geom_point(color='red')
scale_color_identity(name = NULL,
na.translate = FALSE,
標簽 = c("P < 0。 05", "P < 0.10"),
guide = "legend")
facet_wrap(~cyl。 天平= "free")
和上面一樣,你也可以使用這個geom_smooth()命令:
geom_smooth(slope = coef(myline)[[2]]。 攔截= coef(myline) [[1]]/span>。 color='blue',se=F。 method='lm')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/330225.html
標籤:
