在這個說明性資料中:
set.seed(12)
df <- data.frame(
Sequ = c(rep(1,7),rep(2,10),rep(3,14),rep(4,10)),
Q = c(rep("q_pol",7), rep("q_wh",10),rep("q_pol",14),rep("q_wh",10)),
pp = c(rnorm(7), rnorm(10,1), rnorm(14,2), rnorm(10,3))
)
有pp 按Sequ和分組的觀測值Q。我想為這樣的分組繪制線性回歸線pp。這是我能做到的。但是,我還需要通過斜率是負數還是正數來區分回歸線。我可以通過這種方式到達斜坡:回歸線如何相應著色?
library(dplyr)
libraryggplot2)
df %>%
group_by(Sequ) %>%
mutate(x = row_number()) %>%
mutate(slope = lm(pp ~ x)$coeff[2]) %>%
ggplot(
aes(x = x, y = pp, color = as.character(Sequ)))
geom_smooth(method = "lm", se = FALSE)
facet_wrap(. ~ Q, scales = 'free_x')
theme(legend.position = "none")

uj5u.com熱心網友回復:
您可以通過映射條件顏色由斜坡slope > 0上color。由于這改變了默認分組,我們還必須添加group美學以獲得每個回歸線Sequ:
library(dplyr)
library(ggplot2)
df %>%
group_by(Sequ) %>%
mutate(x = row_number()) %>%
mutate(slope = lm(pp ~ x)$coeff[2]) %>%
ggplot(aes(x = x, y = pp, color = slope > 0, group = factor(Sequ)))
geom_smooth(method = "lm", se = FALSE)
facet_wrap(. ~ Q, scales = 'free_x')
theme(legend.position = "none")
#> `geom_smooth()` using formula 'y ~ x'

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406988.html
標籤:
