[英]R: Average trend line for geom_point() in ggplot2 to estimate overall trend?
如何在 geom_point() 中擬合一條線,以估計每個 plot 的總體趨勢。
每條線代表一名具有基線測量(紅點)和第二次測量(藍點)的患者。
p <- ggplot(data = df, aes(x=days, y=temp_1)) +
geom_point(aes(x=days, y=temp_1), color="red", show.legend = TRUE) +
geom_point(aes(x=day, y=temp_2), color="blue", show.legend = TRUE) +
scale_color_manual(name="Measurements", breaks=c("temp_1", "temp_2"), values = c("red", "blue")) +
xlim(0, 20) + ylim(70, 100) +
geom_segment(aes(x=days, y=temp_1, xend=day, yend=temp_2))+
facet_grid(~ treatment) +
theme(legend.position = "bottom")
一種選擇是首先將您的數據重塑為長格式,這可以稍微簡化您的繪圖代碼,並可以輕松地通過geom_smooth
添加趨勢線。
使用一些假的隨機示例數據:
set.seed(123)
n <- 100
df <- data.frame(
days = 0,
day = sample(1:20, n, replace = TRUE),
temp_1 = sample(70:100, n, replace = TRUE),
temp_2 = sample(70:100, n, replace = TRUE),
treatment = sample(c("yes", "no"), n, replace = TRUE)
)
library(ggplot2)
library(dplyr)
library(tidyr)
df <- df %>%
rename(day_1 = days, day_2 = day) %>%
mutate(id = seq(nrow(.))) %>%
pivot_longer(-c(id, treatment), names_to = c(".value", "time"), names_sep = "_")
ggplot(data = df, aes(x = day, y = temp)) +
geom_point(aes(color = time), show.legend = TRUE) +
geom_line(aes(group = id)) +
geom_smooth(method = "lm", se = FALSE) +
scale_color_manual(name = "Measurements", values = c("red", "blue")) +
xlim(0, 20) +
ylim(70, 100) +
facet_grid(~treatment) +
theme(legend.position = "bottom")
#> `geom_smooth()` using formula 'y ~ x'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.