gpt4 book ai didi

r - 使用 geom_smooth 添加回归线以在 R 中使用离散 x 轴绘制

转载 作者:行者123 更新时间:2023-12-04 14:14:54 25 4
gpt4 key购买 nike

我想将线性模型的回归线添加到 R 中的绘图。

我创建了以下示例数据集:

# Load libraries
library(tidyverse)
library(ggbeeswarm)

# Set seed
set.seed(123)

# Create dataset
ID <- sprintf("ID-%s",seq(1:30))
baseline <- rnorm(30, mean = 50, sd = 3)

df <- data.frame(ID, baseline) %>%
mutate(`1` = baseline - rnorm(1, mean = 5, sd = 4),
`2` = `1` - rnorm(1, mean = 7, sd = 5),
`3` = `2` - rnorm(1, mean = 10, sd = 9)) %>%
pivot_longer(-ID) %>%
rename(time = name) %>%
mutate(time = as.factor(time))

创建以下图:

# Plot
ggplot(data = df, aes(x=time, y = value)) +
geom_quasirandom() +
theme_classic() +
scale_x_discrete(limits = c("baseline", "1", "2", "3") ) +
labs(x = "Time", y = "Value")

enter image description here

如果我将 geom_smooth(method = 'lm') 添加到绘图中,什么也不会发生,我认为这与 time 是一个因素有关.但是,添加 geom_smooth(method = 'lm', formula = y~as.numeric(x) 也不起作用。

如何在此图上绘制回归线?

EDIT1.0:我已经能够使用 geom_smooth 通过 geom_smooth(aes(x = as.numeric(time), y = value), method = "lm", formula = y~x) 绘制回归线,但遗憾的是,回归线不正确...

最佳答案

如何使用有序因子来启用 aes(as.numeric(time), value) 的叠加?

# Load libraries
library(tidyverse)
library(ggbeeswarm)

# Set seed
set.seed(123)

# Create dataset
ID <- sprintf("ID-%s",seq(1:30))
baseline <- rnorm(30, mean = 50, sd = 3)

df <- data.frame(ID, baseline) %>%
mutate(`1` = baseline - rnorm(1, mean = 5, sd = 4),
`2` = `1` - rnorm(1, mean = 7, sd = 5),
`3` = `2` - rnorm(1, mean = 10, sd = 9)) %>%
pivot_longer(-ID) %>%
rename(time = name) %>%
# create ordered factor to allow synchronized order of x after as.numeric
mutate(time = factor(time, ordered = T, c("baseline", "1", "2", "3")))


## rendered results
ggplot(data = df, aes(x=time, y = value)) +
geom_quasirandom() +
theme_classic() +
labs(x = "Time", y = "Value") +
geom_smooth(aes(as.numeric(time), value), method = "lm")



## verify with this
ggplot(data = df, aes(x=time, y = value)) +
geom_point() +
theme_classic() +
labs(x = "Time", y = "Value") +
geom_smooth(aes(as.numeric(time), value), method = "lm")

reprex package 创建于 2020-04-15 (v0.3.0)

关于r - 使用 geom_smooth 添加回归线以在 R 中使用离散 x 轴绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61225114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com